简体   繁体   English

简单的C ++汇总程序

[英]Simple C++ Summing Program

This is my first time using C++ and I am writing a small program to sum up to ten numbers (doubles) that will be entered in the command prompt. 这是我第一次使用C ++,并且我正在编写一个小程序以将最多十个数字(双精度)求和,这些数字将在命令提示符下输入。

I have written the following code and I cannot figure out why it will not produce the desired result. 我已经编写了以下代码,但无法弄清楚为什么它不能产生预期的结果。

int main()
{
    double num[10];
    double sum = 0;
    int i;
    int n = 10;

    while (scanf_s("%lf", &num) != EOF)
    {
        for (i = 0; i < n; ++i)
        {
            scanf_s("%lf", &num);
            sum = sum + num[i];
        }
    }

    cout << sum;

    system("pause");
    return 0;
}

The data entry is terminated with a control D. In my eyes it should run fine but it doesn't. 数据输入以控件D终止。在我看来,它应该运行正常,但事实并非如此。 Could someone please give me some pointers for solving this, I don't just want to be told the correct way I would rather learn it myself. 有人可以给我一些解决这个问题的指示,我不只是想被告知我宁愿自己学习的正确方法。

The problem is that &num is the address of the array. 问题是&num是数组的地址。 SO you read your value always in num[0] meaning that num[i] is random in most of the cases. 因此,您始终以num[0]读取值,这意味着num[i]在大多数情况下是随机的。

Try to change your loop: 尝试更改循环:

for (i = 0; i < n && (cin>>num[i]); ++i)
{
    sum = sum + num[i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM