非常多程序猿都認為自己的編程工作十分的鼓噪乏味。一整天面對的都是一些寫不完的代碼和改不完的Bug。今天我們要給大家分享一些有趣的C語言代碼,也許能夠為你無聊的工作帶來一絲樂趣。
這些代碼能夠完畢幾個不同的愛心圖案。當中有一個樣例甚至能夠在黑色背景的控制台上打印出跳動的3D愛心動畫,效果相當震撼。
我用的是Visual Studio 2015開發環境,假設你也使用這個開發環境。能夠直接拷貝以下的代碼進行效果演示。
普通的愛心圖案
C語言代碼:
#include "stdafx.h" #include <math.h> #include <stdio.h> int main() { float y, x, a; for (y = 1.5f;y > -1.5f;y -= 0.1f) { for (x = -1.5f;x < 1.5f;x += 0.05f) { a = x*x + y*y - 1; putchar(a*a*a - x*x*y*y*y <= 0.0f ?'*' : ' '); } putchar('\n'); } return 0; }
效果圖:
帶花紋的愛心圖案
C語言代碼:
#include "stdafx.h" #include <math.h> #include <stdio.h> int main() { float y, x, z,f; for (y = 1.5f;y > -1.5f;y -= 0.1f) { for (x = -1.5f;x < 1.5f;x += 0.05f) { z = x*x + y*y - 1; f = z*z*z - x*x*y*y*y; putchar(f <= 0.0f ? ".:-=+*#%@"[(int)(f*-8.0f)] : ' '); } putchar('\n'); } getchar(); return 0; }
效果圖:
跳動的3D愛心圖案
C語言代碼:
#include "stdafx.h" #include <stdio.h> #include <math.h> #include <windows.h> #include <tchar.h> float f(float x, float y, float z) { float a = x * x + 9.0f / 4.0f * y * y + z * z - 1; return a * a * a - x * x * z * z * z - 9.0f / 80.0f * y * y * z * z * z; } float h(float x, float z) { for (float y = 1.0f; y >= 0.0f; y -= 0.001f) if (f(x, y, z) <= 0.0f) return y; return 0.0f; } int main() { HANDLE o = GetStdHandle(STD_OUTPUT_HANDLE); _TCHAR buffer[25][80] = { _T(' ') }; _TCHAR ramp[] = _T(".:-=+*#%@"); for (float t = 0.0f;; t += 0.1f) { int sy = 0; float s = sinf(t); float a = s * s * s * s * 0.2f; for (float z = 1.3f; z > -1.2f; z -= 0.1f) { _TCHAR* p = &buffer[sy++][0]; float tz = z * (1.2f - a); for (float x = -1.5f; x < 1.5f; x += 0.05f) { float tx = x * (1.2f + a); float v = f(tx, 0.0f, tz); if (v <= 0.0f) { float y0 = h(tx, tz); float ny = 0.01f; float nx = h(tx + ny, tz) - y0; float nz = h(tx, tz + ny) - y0; float nd = 1.0f / sqrtf(nx * nx + ny * ny + nz * nz); float d = (nx + ny - nz) * nd * 0.5f + 0.5f; *p++ = ramp[(int)(d * 5.0f)]; } else *p++ = ' '; } } for (sy = 0; sy < 25; sy++) { COORD coord = { 0, sy }; SetConsoleCursorPosition(o, coord); WriteConsole(o, buffer[sy], 79, NULL, 0); } Sleep(33); } }
效果圖
跳動的愛心動畫須要你執行程序后才干夠看到。