我试图创建一个代码,但似乎它在sum的输出上返回了一个错误的值

时间:2016-01-17 04:58:50

标签: c

以下是我用c语言编写的代码,我一直在更改代码并将x=ay=b放在源代码的不同位置,但情况更糟。

#include<stdio.h>
main()
{
    int sum, a=3, b=5, x=0, y=0;

    while(a<10){
        printf("\n%d",a);
        a+=3;
        x=a;
        if(a>10){
            goto c;
        }
    }
    c:
    while(b<10){
        printf("\n%d",b);
        b+=5;
        y=b;
        if(b>10){
            return 0;
        }
    }
    sum=x+y;
    printf("\nSum is %d", sum);

}

很明显,总和必须是23,但它返回22:

3
6
9
5
Sum is 22

2 个答案:

答案 0 :(得分:0)

查看代码,有答案......

#include<stdio.h>
main()
{
    int sum, a=3, b=5, x=0, y=0;

    while(a<10){
        printf("\n%d",a);
        a+=3;
        x=a;
        if(a>10){
            goto c;
        }
    }
    c:
    while(b<10){
        printf("\n%d",b);
        b+=5;
        y=b;
        if(b>10){
            return 0;
        }
    }
    sum=x+y;
    printf("\nSum is %d", sum);

}



    While a < 10... 

before store 3 inside x, you increase a to 3 (3+3=6), then you store 6 inside x
after that, you add 3 to a (6+3=9) and store it inside x...
after that, you add 3 to a (9+3=12) and stores it inside x... 
x = 6
x = 9
x = 12
You never store 3 inside x and then you store 12, one step further

and the you go to c (goto c;), and you keep 12 inside x... 

    while b < 10... 

b = 5... but you increase in 5... then you got 10 inside b... 
And then you store it inside y... 
and then... 10 is not less than 10 (because 10 is equal to 10) you go out the loop

and then you got... 
    x = 12
+   y = 10
------------
=       22

这就是为什么你得到22而不是23 ......

的原因

但这是得到23的答案

#include <stdio.h>

int main(int argc, const char * argv[]) {
    int sum, a=3, b=5, x=0, y=0;

    while(a<10)
    {
        printf("\n%d",a);
        x+=a; //x = x + a
        a+=3;
        if(x>10){
            goto c;
        }
    }
c:
    while(b<10)
    {
        printf("\n%d",b);
        y+=b; // y = y + b //but this run just once
        b+=5;
        if(y>10){
            return 0;
        }
    }
    sum=x+y;
    printf("\nSum is %d", sum);
}

答案 1 :(得分:-1)

根据您的评论,这将为您提供3 + 6 + 9 + 5 = 23

#include<stdio.h>
main()
{
    int sum, a=3, b=5, x=0, y=0;

    while(a<10){
        x+=a;
        a+=3;
        printf("\n%d ",x);
        if(x>10){
            goto c;
        }
    }
    c:
    while(b<10){
        y=b;
        b+=5;
        printf("\n%d",y);
        if(b>10){
            return 0;
        }
    }
    sum=x+y;
    printf("\nSum is %d", sum);

}