3

I have a program that reads in 5 integers and gives out results of various calculations using those numbers. I am having particular trouble calculating the geometric mean. I am aware that you are supposed to multiply the numbers together and take the nth root of the result.

my code is as follows (assume all #includes and main method are correct.):

int num1, num2, num3, num4, num5;

cout << "Enter five integers: \n";
cin >> num1 >> num2 >> num3 >> num4 >> num5;

double gMean = pow((num1 * num2 * num3 * num4 * num5), (1.0/5.0));
cout << "Geometric mean     = " << gMean << endl;

This code works for small numbers, such as 1, 2, 3, 4, 5, but when I input large numbers it gives me nan as the answer.

The numbers I need to work in this are : 85, 43, 95, 100, and 78

My question is: Why does the pow() function give me nan as the answer when the larger numbers are put in but return the correct answers when small numbers are put in?

EDIT: First question answered. Now that I know that I am having overflow issues, how do I go about resolving it?

4

4 回答 4

6

从手册页pow(x,y)

   If x is a finite value less than 0, and y is a finite noninteger, 
a domain error occurs, and a NaN is returned. 

   Except as specified below, if x or y is a NaN, the result is a NaN.

   If x is negative, then large negative or positive y values yield a NaN 
as the function result, with  errno  set  to  EDOM,  and  an  invalid
   (FE_INVALID)  floating-point  exception.  For example, with pow(), 
one sees this behavior when the absolute value of y is greater than about
   9.223373e18.

所以在你的情况下看起来像第一个案例。

于 2013-09-17T05:03:27.863 回答
2

为了(可能)避免溢出,重写为

double gMean = pow(num1, (1.0/5.0)) *
               pow(num2, (1.0/5.0)) *
               pow(num3, (1.0/5.0)) *
               pow(num4, (1.0/5.0)) *
               pow(num5, (1.0/5.0)) 
于 2013-09-17T05:08:27.803 回答
2

问题不在pow. 表达方式

num1 * num2 * num3 * num4 * num5

本身就是罪魁祸首。如果您在调试器中查看结果值,您可能会看到一些无意义的负值。这就是pow失败的原因。如果第一个参数为负且第二个参数不是整数,则失败并出现域错误。

85、43、95、100和78的产品不适合int您平台的范围。它溢出并导致未定义的行为。这是你观察到的。

将该表达式的值计算为

(double) num1 * num2 * num3 * num4 * num5

pow应该给出一个更有意义的结果。

于 2013-09-17T05:32:52.147 回答
1

你溢出了双倍可以存储的东西。数字太大,导致您输入的双打溢出。

此外,您可以根据此处文档中所述的错误期间发生的一些事件检查这些问题:http: //en.cppreference.com/w/cpp/numeric/math/pow

为清楚起见进行了编辑: pow() 将双精度作为输入,因此当您将所有这些整数相乘时,当结果类型转换为双精度时,可能会导致溢出。此外,数学本身可能会导致溢出。

于 2013-09-17T04:57:50.343 回答