C++ 如何对一串数字求平均值
C++ How to average a string of numbers?
我对我试图解决的事情有问题。
如果我有一串带有空格的数字,例如"10 20 30 40",有什么方法可以将这些数字相加并将它们平均出来?
我尝试了下面的代码,但它返回了"nan",所以我真的不知道我做错了什么。
for (int i = 0; i < numLength; i++)
{
num = grades.at(i) - '0';
total += num;
countNum++;
}
cout << firstName << " " << lastName << " average: " << (total/countNum) << endl;
与其尝试手动解析数据,不如简单地使用 std::istringstream:
#include <string>
#include <sstream>
#include <iostream>
int main()
{
std::string test = "10 20 30 40";
int count = 0;
double total = 0.0;
std::istringstream strm(test);
int num;
while ( strm >> num )
{
++count;
total += num;
}
std::cout << "The average is " << total / count;
}
输出:
The average is 25
使用std::istringstream
来解析字符串,例如:
#include <iostream>
#include <string>
#include <sstream>
...
std::istringstream iss(grades);
while (iss >> num) {
total += num;
++countNum;
}
std::cout << firstName << " " << lastName << " average: " << (total/countNum) << std::endl;
相关文章:
- 程序以使用 C++ 中的 while 循环查找一组数字的最小值
- C++为一串单词添加空格
- 斐波那契数列部分和的最后一位数字
- 为什么Visual Studio正在清除我的一串反斜杠
- 如何检查cin是否与数组中的一组数字匹配
- 如何将内存中的位转换为一串和零?
- 如何返回一串字母数字字符中的最大值(例如-1A003B3)?
- 如何找到由公式计算的非常大的数字的最后一位数字?
- 创建一个程序,该程序将一串数字作为输入,并输出偶数和奇数的总和
- C++ 如何对一串数字求平均值
- 从一串数字C++创建一个数字序列
- 在另一个字符串中查找一串数字
- 将一串数字分解为26以下数字的计数方法
- 将一串数字转换为整数向量 c++
- 将一串数字转换为任何形式的整数
- 如何压缩一串数字
- 如何将数字"Bind"到一串单词/短语中,以便我可以循环调用它?
- 将一串数字解析为int向量的最快方法
- 解析一串数字
- 将一串数字转换为二进制