0

如果有一个名为 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,尽管这并不重要。

4

2 回答 2

0

这应该可行。在您的程序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);
于 2013-05-02T09:30:55.343 回答
0

你可能会喜欢这个。

#include <stdio.h>
#include <stdbool.h>

int getA(){
    static int count = 1;
    if(count == 1000) count = 1;
    return count++;
}

int main(void){
    int i = 0;
    int a, total;

    while (true) {
        a = getA();
        if(i == 1001) break;
        total += a;
         ++i;
    }
    printf("%d\n", total);//499501 = 1+2+...998+999+1
    return 0;
}
于 2013-05-02T09:20:32.773 回答