c++ - 计算用户使用循环输入的整数数量

标签 c++ loops integer using counting

#include <iostream>
int main()
{
  int cnt = 0, sum = 0, value = 0;
    std::cout << "Please enter a set of numbers and then press ctrl+z and ENTER to add the numbers that you entered" << std::endl;
    if (cnt = value) 
    ++cnt;          
    while (std::cin >> value)

       sum += value;  

    std::cout << "the sum is: " << sum << std::endl;
    std::cout << "the amount of numbers you entered are: " << cnt << std::endl;

    return 0;

}

我的 if 语句是错误的,并且没有计算用户输入值的整数数量。

如何让程序计算用户使用循环输入的整数数量?

最佳答案

解决方案说明

为了计算所提供的整数的数量,只需在给出新输入时将 1 添加到 cnt 即可。 (请参阅下面带有//** 注释的行)。

此外,不需要在开始时进行 cnt==value 检查(并且缺少一个“=”字符)。

更新代码

总而言之,您的代码应更改如下:

#include <iostream>
int main()
{
    int cnt = 0, sum = 0, value = 0;
    std::cout << "Please enter a set of numbers and then press ctrl+z and ENTER to add the numbers that you entered" << std::endl;      
    while (std::cin >> value)
    {
       sum += value;  
       cnt++; //**
    }
    std::cout << "the sum is: " << sum << std::endl;
    std::cout << "the amount of numbers you entered are: " << cnt << std::endl;

    return 0;

}

关于c++ - 计算用户使用循环输入的整数数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094127/

相关文章:

c# - 如何获取属性名称及其值?

java - 从 1D 获取 2D 数组索引

python - 有什么办法可以让整数被归类为没有 .0 的整数,而 float 被归类为 float 吗?

python - 如何从 float 列表中获取 python 中整数的最大公约数?

rust - 如何将负 i32 数添加到 usize 变量?

c++ - 使用boost的timed_wait?

c++ - 插入 map 库无效

Python:如何从for循环返回数据?

c++ - 在 C++ 中组合接口(interface)

c++ - 如何使用 C++ 在 OpenGL_POINTS 函数中绘制正弦波