2012-08-28 115 views
1

这是我第一次使用c语言编程。我有这样的代码,应该采取用户输入的任何数字,直到输入0.然后它应该将它们全部加起来。例如,如果他们输入1,然后是2,然后是3,最后是0,则应输出6.但由于某种原因,它不会添加最后一个值。在这种情况下我提到这将打印3而不是6C使用while循环添加输入

#include <stdlib.h> 
#include <stdio.h> 

static char syscall_buf[256]; 
#define syscall_read_int()   atoi(fgets(syscall_buf,256,stdin)) 

main() 
{ 
    int input; 
    input = syscall_read_int(); 

    int result = 0; 
    input = syscall_read_int(); 
    while (input != 0){ 
     result = result + input; 
     input = syscall_read_int(); 
    } 
    printf("%i\n", result); 
} 
+1

摆脱无关的'input = syscall_read_int();'行。 –

回答

1

您在第10行有一个额外的syscall_read_int()。无论如何,我建议您使用do-while循环,因为您需要读取至少一个整数。下面的代码使用do-while循环:1 + 2 + 3 + 0 = 6

#include <stdlib.h> 
#include <stdio.h> 

static char syscall_buf[256]; 
#define syscall_read_int()   atoi(fgets(syscall_buf,256,stdin)) 

main() 
{ 
    int input; 
    int result = 0; 

    do { 
     input = syscall_read_int(); 
     result = result + input; 
    } while(input != 0); 

    printf("%i\n", result); 
} 
1

你有这个函数的额外调用:syscall_read_int()。尝试调试并查看发生了什么。

您正在覆盖变量int input的值;因此,你不能在你提到的具体情况添加的第一个值的变量int result

插入1,然后2,然后3终于0。第一个值 - 1 - 未被添加,因此程序将打印5(2 + 3)而不是6(1 + 2 + 3)。

这就是问题所在,试试这个:

#include <stdlib.h> 
#include <stdio.h> 

static char syscall_buf[256]; 
#define syscall_read_int()   atoi(fgets(syscall_buf,256,stdin)) 

main() 
{ 
    int input; 
    //input = syscall_read_int(); //you need to comment this line 
    int result = 0; 
    input = syscall_read_int(); 
    while (input != 0){ 
     result = result + input; 
     input = syscall_read_int(); 
    } 
    printf("%i\n", result); 
} 

希望它能帮助!

0

当你的程序被写入时,它会丢失你输入的第一个值(它什么都不用),所以如果你输入1,2,3,它会返回5,而不是3。在代码的最后运行带有额外syscall_read_int()的版本?