标题:书中的例题:在 for 循环中使用 scanf()对数列进行求和,为什么运行出错?
只看楼主
muyoucumian
Rank: 3Rank: 3
等 级:等待验证会员
帖 子:80
专家分:126
注 册:2014-8-30
结帖率:100%
已结贴  问题点数:20 回复次数:2 
书中的例题:在 for 循环中使用 scanf()对数列进行求和,为什么运行出错?
谢谢各位高手回帖指明原因!

下面的这个小程序是《C程序设计_现代方法》第二版第六章的一个对数列进行求和的例题。

我把这个程序输入code:blocks后编译后再运行却出错,表现为输入2 3回车后没反应,再回车多少次都没反应。单步调试时表现为n一直取2不变,然后sum从2到4到6一直递增。

我google了一下scanf函数陷阱、for循环中的scanf使用,没发现有用的答案。
下面是程序*****************************************************************************************************************************************

//用户输入整数,中间以空格分割,以回车结束。程序计算出所有这些整数的和。
#include <stdio.h>

int main()
{
    int n, sum = 0;

    printf("This program sums a series of numbers.\n");
    printf("Enter numbers (0 to terminate): ");

    scanf("%d", &n);
    while(n != 0.0){
        sum += n;
        scanf("d", &n);
    }

    printf("The sum is: %d.\n", sum);
    return 0;
}
搜索更多相关主题的帖子: C程序设计 google 用户 
2014-08-30 11:13
wssy213
Rank: 12Rank: 12Rank: 12
来 自:湖南
等 级:贵宾
威 望:10
帖 子:967
专家分:3703
注 册:2014-6-6
得分:20 
#include <stdio.h>

int main()
{
    int n, sum = 0;

    printf("This program sums a series of numbers.\n");
    printf("Enter numbers (0 to terminate): ");

    scanf("%d", &n);
    while(n != 0.0){
        sum += n;
        scanf("d", &n);
    }

    printf("The sum is: %d.\n", sum);
    return 0;
}

坚持----------------------------------唯一的道路
shit ! ! !
2014-08-30 12:15
muyoucumian
Rank: 3Rank: 3
等 级:等待验证会员
帖 子:80
专家分:126
注 册:2014-8-30
得分:0 
回复 2 楼 wssy213
谢谢!!是我太粗心了
2014-08-30 12:37



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-435504-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.413380 second(s), 7 queries.
Copyright©2004-2025, BCCN.NET, All Rights Reserved