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

Ses*_*ame 3 c++ math

我在尝试解决某些问题。

如果我有一串带有空格的数字,例如“ 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;
Run Code Online (Sandbox Code Playgroud)

Pau*_*zie 6

无需尝试手动解析数据,只需使用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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

The average is 25
Run Code Online (Sandbox Code Playgroud)