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

count the amount of integers the user enters using a loop

本文关键字:整数 数数 输入 循环 用户 计算      更新时间:2023-10-16
#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==值检查(并且那里缺少一个"="字符(。

更新的代码

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

#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;
}