Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
158 views
in Technique[技术] by (71.8m points)

c - Sum of primes: what is the problem in result?

The code works fine but why are my answers wrong in the int result?

in output:

3
10
2 3 5 7: 17  //correct
30
2 3 5 7 11 13 17 19 23 29: 146  //incorrect
50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47: 474   //incorrect

Here is the code:

#include <stdio.h>

int main() {
    int y, n, i, fact, j, result = 0;
    scanf("%d", &y);
    for (int x = 1; x <= y; x++) {
        scanf("%d", &n);
        for (i = 1; i <= n; i++) {
            fact = 0;
            for (j = 1; j <= n; j++) {
                if (i % j == 0)
                    fact++;
            }
            if (fact == 2) {
                result += i;
                printf("%d ", i);
            }
        }
        printf(": %d
", result); //Not Getting correct answer please HELP!
    }
    return 0;
}
question from:https://stackoverflow.com/questions/66051375/sum-of-primes-what-is-the-problem-in-result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You forgot to initialize result before each calculation.

for(int x=1;x<=y;x++){
    scanf("%d", &n);
    result = 0; // add this for initialization
    for (i = 1; i <= n; i++) {
        /* ... */
    }
    /* ... */
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...