m0_46100284
m0_46100284
2021-01-18 16:05
采纳率: 100%
浏览 2

一个求和的程序,运行结果总是比正确答案大1,是编译器的问题吗?

c primer plus第六章第一个程序,我按书上的程序往电脑里输入的,最终运行的结果总是比正确答案大1。我用的是DEVC++

//summing.c --根据用户键入的整数求和

#include <stdio.h>
int main(void)
{
    long num;
    long sum = 0L;
    int status;
    
    printf("Please enter an integer to be summed ");
    printf("(q to quit): ");
    status = scanf("%ld", &sum);
    while (status == 1)
    {
        sum = sum + num;
        printf("Please enter next integer (q to quit): ");
        status = scanf("%ld",&num);
        
    }
    printf("Those integers sum to %ld.\n",sum);
    
    return 0;
}
 

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • weixin_43621710
    jonker_M 2021-01-18 16:10
    已采纳

    初始化一下num=0 或者将第一个scanf里的&sum改为&num

    点赞 评论
  • qq_25376897
    qq_25376897 2021-01-18 16:10
    #include <stdio.h>
    int main(void)
    {
        long num;
        long sum = 0L;
        int status;
        
        printf("Please enter an integer to be summed ");
        printf("(q to quit): ");
        status = scanf("%ld", &num);//这里是num,不是sum
        while (status == 1)
        {
            sum = sum + num;
            printf("Please enter next integer (q to quit): ");
            status = scanf("%ld",&num);
            
        }
        printf("Those integers sum to %ld.\n",sum);
        
        return 0;
    }
    点赞 评论

相关推荐