0

所以在这个程序中,我试图打印出用户输入的一组数字的标准偏差。计算标准偏差的公式是正确的(或正确的)所以这不是问题,但是当我运行程序一切顺利,直到控制台打印出结果。它打印出 totalStandardDeviation = nan

究竟是什么意思?nan 和 nil 一样吗?它是否以某种方式失去了价值并且无法找到它?感谢您提供的任何帮助。

#include <iostream>
#include <cmath>
using namespace std;

double returnStandardDeviation(double x, int counter);
double total;

int userInput = 1;
int counter = 0;
double x;
double x1;
double x2;

double standardDeviation;
double totalStandardDeviation;

int main(int argc, const char * argv[])
{
    cout << "Please enter a list of numbers. When done enter the number 0 \n";
    cin >> userInput;

    while (userInput != 0)                         // As long as the user does not enter 0, program accepts more data
    {
        counter++;
        x = userInput;
        returnStandardDeviation( x, counter);       // send perameters to function

        cout << "Please enter next number \n";
        cin >> userInput;
    }

    cout << "The standard deviation of your "
    << counter
    << " numbers is : "
    << returnStandardDeviation(x, counter);
    return 0;
}


double returnStandardDeviation(double x, int counter)
{
    x1 += pow(x,2);
    x2 += x;
    totalStandardDeviation = 0;
    totalStandardDeviation += (sqrt(counter * x1 - pow(x2,2))) / (counter * (counter - 1));
    return totalStandardDeviation;
}
4

4 回答 4

1

NaN代表“不是数字”。

于 2013-10-28T06:46:36.090 回答
1

例如, NaN可以是以下结果:

- Dividing by zero
- Taking the square root of a negative number 

在您的功能中,这两种情况都可能发生。除以零,例如当counteris <= 1; 和x1并且x2未初始化(+=将右侧的值添加到它们的当前值 - 从未设置过,因此是随机的乱码),这很容易导致您的函数试图取某个值 < 0 的平方根。

于 2013-10-28T06:48:53.803 回答
1

这个表达

counter * x1 - pow(x2,2)

可以很容易地产生一个负数。然后你继续取它的平方根。这将导致一个nan.

接下来这个

counter * (counter - 1)

0counter是时产生1。除以零给出nan

于 2013-10-28T06:53:27.997 回答
0

你的公式是错误的。您要么除以零,要么取负数的平方根。

检查你的公式!

附加信息:

NaN 是“不是数字”。它是一个 IEEE 浮点值,表示无效结果,如 log(-1) 或 sqrt(-4)。

此外,要知道正无穷大和负无穷大也是浮点值。

于 2013-10-28T06:50:21.237 回答