使用增量/减少操作员在C 中显示数组的奇怪结果

Strange result of displaying array using increment/decrement operator in C++

本文关键字:数组 显示 结果 操作员      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
    double donation[10];
    int index = 0;
    cout.setf(ios::fixed);
    cout << "Enter sum of money for donating: ";
    while (index < 10 && cin >> donation[index])
    {
        cout << "donation #" << 1 + index++ << ": " << donation[index] << endl;
    }
    return 0;
}

结果

该代码无法显示捐赠的正确值...

我可以检查错误是" 1 索引 ",但我不知道为什么这样做。

为什么我使用'1 index '的代码在下一行中使用'index '时与代码有所不同。

应避免使用惯用方式,而不是试图理解陌生人构造,还应避免将增量与功能/操作员参数混合(请参阅序列点(:

for (int index = 0; index < 10; ++index)
{
   if (! std::cin >> donation[index])
        break;
   std::cout << "donation #" << (1 + index) << ": " << donation[index] << std::endl;
}

这应该做期望的事情,应该通过对C 的知识来理解。它最多运行10次,试图填充输入到数组,并在输入失败时输入起作用或停止时显示。唯一的问题将是对用户输入的更好验证。