我在循环时无法弄清楚这一点。我理解这个概念,我不知道该怎么做才能增加它。另外,由于某种原因,我的跑步总数不起作用?
这背后的想法是设定一个存钱的目标。每次我在罐子里放一定数量的钱,我都希望它能给我罐子里的总金额,还告诉我需要多少钱放在罐子里才能达到我的目标。
这是我的代码:
#include <stdio.h>
int main() {
int goal;
int total = 0;
int deposite;
int ammountNeeded;
printf("How much money would you like to save?\n ");
scanf("%i", &goal);
printf("How much money are you putting in the jar?\n");
scanf("i%", &deposite);
total = total + deposite;
ammountNeeded = goal - deposite;
while (goal > total) {
printf("How much money are you putting in the jar?\n ");
scanf("i%", &deposite);
printf("You have saved R%i. ", total);
printf("You need to save another R%i in order to reach your goal.\n ",ammountNeeded);
}
if (total >= goal) {
printf("Well done! you have sucsessfully saved R%i", goal);
}
return 0;
}
答案 0 :(得分:3)
while循环有一个条件。只要条件为真,它就会执行主体。在您的情况下,条件不会更改,因为比较的2个变量都不会更改其在循环内的值。你应该增加总数或减少目标。
答案 1 :(得分:0)
这应该解决它:
while (goal > total) {
printf("How much money are you putting in the jar?\n ");
scanf("i%", &deposite);
total = total + deposite; //Add this
printf("You have saved R%i. ", total);
ammountNeeded = goal - total; // And perhaps add this
printf("You need to save another R%i in order to reach your goal.\n ",ammountNeeded);
}