C++ 如何对一串数字求平均值

C++ How to average a string of numbers?

本文关键字:一串 数字 平均值 C++      更新时间:2023-10-16

我对我试图解决的事情有问题。

如果我有一串带有空格的数字,例如"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;