如果有一个名为a的变量,它不断地向上计数,但是当达到某个数字时又重置为0,我该如何计算该变量的总数?例如:
int count = 0;
int a = 0;
int total = 0;
while (true) {
count++;
a = count % 1000;
total = ...;
}
其中“total”是a的总值,它会超过1000。简单地添加它是行不通的,因为它会变成total+=1、total+=2、total+=3等等。怎么办?我每次循环都计算这个?谢谢你的帮助。 :) 顺便说一句,我正在使用 C,尽管这并不重要。
最佳答案
这应该可行。在您的程序中,total
与 a
的值没有任何关系。
int count = 1;
int a = 0;
int total = 0;
while ((count+1001)%1001) {
a = (count+1001) % 1001;
count++;
total = total+a;
}
printf("The sum of 1000 numbers is %d",
total);
关于c - 如何计算递增变量的总计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16334101/