优雅的while小故事

include <stdio.h>

include <windows.h>

include <inttypes.h>

void while_story_1();

void while_story_2();

void while_story_3();

void while_story_4();

int main(void) {

复制代码
SetConsoleOutputCP(65001);
printf("Hello, World!\n");
while_story_1();
while_story_2();
while_story_3();
while_story_4();

return 0;

}

void while_story_1()

{

//减肥

float weight = 103;

float target_weight = 98;

while(weight > target_weight)

{

printf("我需要减肥!,目标体重是: %.1f\n",target_weight);

printf("锻炼!\n");

float temp = weight;

weight = weight - 0.5;

printf("我之前的体重是: %.1f,现在的体重是: %.1f\n",temp,weight);

printf("减肥成功1次!\n\n\n");

}

printf("减肥成功!,我现在的体重是: %.1f\n\n",weight);

}

void while_story_2()

{

//成为拥有一块钱的人

float target = 1;

float now_I_earn = 0;

while(now_I_earn < target)

{

printf("想办法!\n");

printf("执行!\n\n");

now_I_earn += 0.01;

}

printf("成功完成目标!\n");

printf("成功赚到%.2f的钱!\n\n",now_I_earn);

}

void while_story_3()

{

//成为拥有分数的人

uint32_t grade_target = 1400;

uint32_t grade_now = 0;

while(grade_now < grade_target)

{

printf("Practice code!\n");

grade_now += 50;

}

printf("Success finish this task!\n");

printf("Now grade is %" PRIu32 "\n\n",grade_now);

}

void while_story_4()

{

//罚跑圈

uint8_t the_circle_need_to_run = 100;

uint8_t the_circle_now_finished = 0;

复制代码
while(the_circle_now_finished < the_circle_need_to_run)
{
    printf("RUN ONE CIRCLE!\n");
    the_circle_now_finished += 1;
}
printf("FINISHED!\n");
printf("Game over, it is too hard to run。\n");

}

某AI的评价:这段代码虽功能完整,但如璞玉待琢。优雅的代码应如精密的机械,每个齿轮都恰如其分。浮点数用于循环控制存在精度风险,0.1+0.2≠0.3的幽灵随时可能浮现。将货币和体重计算改用整数基单位(分、0.1公斤),即可驱散这隐形的魔鬼。

函数命名是代码的门面,while_story_1如无名的路人,若改为lose_weight_journey则瞬间生动。魔法数字散落各处,将它们归入#define的殿堂,代码便获得了自我解释的智慧。

循环体内输出语句过多,可将进度提示封装成print_progress()函数,让主逻辑保持苗条。uint8_t用于100尚可,但若需求变化至300,这狭小的容器便会溢出------uint16_t才是更稳健的选择。

最微妙的是重复的模式:四个故事本质都是"从A到B的渐进之旅"。若能抽象出统一的progress_tracker结构体和achieve_goal()函数,代码便从重复的匠气升华为优雅的匠心。