2017-07-03 4 views
0

5をnとpとして2を書くときはいつも、出力は24 ...私に何が間違っているか教えてください。それ以外の数字は完全にうまくいきます。C++のpowメソッドの5の威力にエラーがあります

#include<iostream> 
#include<conio.h> 
#include<math.h> 
using namespace std; 

int main() 
{ 
    double n, p; 
    cout << "enter the number" <<endl; 
    cin >> n; 
    cout << "enter the power" <<endl; 
    cin >> p; 
    int result = pow(n, p); 
    cout << "Result is " << result; 
    return 0; 
} 
+3

'ダブル、おそらく' 24.999999999 .... '、あなたが' int'でそれを保存するとき、 '24'をされるが、私は再現できません:http://ideone.com/jPgljt – mch

+1

詳細な答えhttps://stackoverflow.com/a/25678721/3701834 – aniliitb10

答えて

0

データタイプに問題があります。

double n, p; // here you use double types 
std::cout << "enter the number" << std::endl; 
std::cin >> n; 
std::cout << "enter the power" << std::endl; 
std::cin >> p; 
int result = pow(n, p); // then here you use double pow(double, double) but assign it to an int 
std::cout << "Result is " << std::result; 

ソリューション:返しpow`

double result = pow(n, p); 
+0

それは問題を解決しません。電源のパラメータが2倍であれば、同様の問題に直面する可能性があり、正確な電力を得ることはできません。 – aniliitb10

+0

@ aniliitb10数値アルゴリズムが実際の数値の正確な値を与えない(値を四捨五入している)ということは、それも事実です。 – Adam

関連する問題