【问题标题】:C++ Reading an unknown number of integers to cin and outputting the sumC ++将未知数量的整数读取到cin并输出总和
【发布时间】:2019-02-06 12:41:35
【问题描述】:

我是 C++ 的新手,我正在尝试编写我自己的程序版本,用于打印从 cin 读取的未知数量的整数的总和。

我介绍的唯一预处理器指令是#include <iostream>

#include <iostream>

int main()
{
    int numbers;
    int sum = 0;

    for (int i = 0; i < numbers; i++)
    {
        std::cin >> i;
        sum += i;
    }
    std::cout << sum << std::endl;

    return 0;
}

输出

cl /EHsc /W4 sum_of_set_of_integers.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.14.26433 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

sum_of_set_of_integers.cpp
a:\c++ tutorial\michael_dawson\sum_of_set_of_integers.cpp(8) : warning C4700: uninitialized local variable 'numbers' used
Microsoft (R) Incremental Linker Version 14.14.26433.0
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:sum_of_set_of_integers.exe
sum_of_set_of_integers.obj

A:\C++ Tutorial\Michael_Dawson>sum_of_set_of_integers
1
1
1
1
1

我无法跳出循环。如果您能提供建议,那将很有帮助..

非常感谢。

【问题讨论】:

  • 你有代表结束的数字吗?
  • 你忘了用合理的值初始化numbers:int numbers;
  • for (int i = 0; i &lt; numbers; i++) 你认为numbers 的值是多少?您从未阅读过它,也没有将其设置为任何内容。

标签: c++ visual-studio loops cin


【解决方案1】:

这里的根本问题是你事先不知道有多少整数会进来,所以你不能使用for循环——numbers没有合理的价值。

相反,继续读取值直到输入结束:

while (std::cin >> i)
    sum += i;

当尝试读取最终失败时,while 循环将退出。

【讨论】:

  • 这是有道理的。非常感谢。
  • 使用 CTRL + Z(行尾)
【解决方案2】:

编译器建议,请仔细阅读。

a:\c++ tutorial\michael_dawson\sum_of_set_of_integers.cpp(8) : warning C4700: uninitialized local variable 'numbers' used

也请尽量遵循 0-errors 和 0-warnings 的原则。

使用 while 循环继续读取和添加整数,直到输入结束。更新后的代码应如下所示:

int main()
{
    int sum = 0;
    while (std::cin >> i)
        sum += i;
    std::cout << sum << std::endl;

    return 0;
}

【讨论】:

  • 我宁愿小心地告诉初学者代码“应该”看起来像什么,特别是当它有 std::cin 时,实际上应该带有错误检查等,只是说......
  • 更改代码的目的/行为不是答案,恕我直言
  • @Korni - 我不明白我是如何改变行为/目的的?请建议
  • @Rizwan OP 问:>“[...] 打印从 cin 读取的未知数量的整数的总和”。在您的版本中,数字是在开头设置的
  • @Korni - 绝对正确。我错过了这一点。谢谢指点。更新了答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 2013-02-12
  • 2014-07-25
  • 2022-09-28
  • 1970-01-01
  • 2013-11-09
相关资源
最近更新 更多