2017-08-31 2 views
6

私はCプログラミングの新機能です。主にprintf()とscanf()を使って何かをするように求められているので、このコードを書いています。私はすぐに学習する必要がありますされ、これを処理するためのより良い方法があるかもしれませんけど、とにかく、今のところこれは私が持っているものです。なぜpow()は私の結果から1を引いていますか?

int add1, add2, exponent, exponent_result, multiplier, parenthese, product, sub, total; 

printf("Let's try a slightly more complex calculation, in which we'll use an exponent.\n\n"); 
printf("Type 5 whole numbers or integers.\n\n"); 
scanf("%i %i %i %i %i", &add1, &add2, &exponent, &multiplier, &sub); 
printf("Out of the numbers you typed, we're going to make this operation: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub); 

exponent_result = pow(add2, exponent); 
parenthese = add1 + exponent_result; 
product = parenthese * multiplier; 
total = (add1 + exponent_result) * multiplier - sub; 

printf("Per PEMDAS, the correct order of operation is Parentheses, then Exponents, then Multiplications and Divisions, and finally Additions and Subtractions.\n\n"); 
printf("Therefore: (%i + %i^%i) * %i - %i\n\n", add1, add2, exponent, multiplier, sub); 
printf("...is equal to: (%i + %i) * %i - %i\n\n", add1, exponent_result, multiplier, sub); 
printf("...is equal to: %i * %i - %i\n\n", parenthese, multiplier, sub); 
printf("...is equal to: %i - %i\n\n", product, sub); 
printf("...is equal to: %i", total); 

このコードを実行する場合は、あなたがいることを実現しますpow() functionを使用して計算されたexponent_resultの出力は、常に1から減算されます。たとえば、exponent_resultが5^3の結果であるとすると、その結果は125の代わりに124になります。

私は間違っていますか?

Fyi、これは私のファイルの冒頭にあります。

#include <stdio.h> 
#include <math.h> 
+0

問題を確認しましたか?私はあなたのプログラムを実行しようとしていたので、うまく動作します。問題なし。あなたがまだ問題を共有している場合は、問題を確認できるように、オンラインで実行可能なコードを共有してください。私は適切な出力を得た。あなたが置かれているものを入力し、特定の問題を抱えていることを言いたいのか? –

+0

は、整数計算にフロートatirthmeticsを使用しようとしません。整数は常に正確です。浮動小数点はほとんど常にそうではありません。私は切り捨て、ラウンド代わりに 'exponent_result = lround(POW(ADD2、指数))を避け –

+1

;' – chux

答えて

7

pow浮動小数点演算で評価され、そしておそらくpow(x, y) = exp(y * log(x))として実装されます。

これは、結果が「消灯」することがあります:あなたはおそらくpowからdouble戻り値の型はバックintに変換されると124に切り捨てられ125のちょうど内気な値を、取得します。

最も簡単な救済策は不可欠な引数のために、独自のpow機能を構築することです。 The most efficient way to implement an integer based power function pow(int, int)

+0

は基数がしばしばことをトリガーとして5' '使用しているようです:https://stackoverflow.com/questions/45960102/inaccurate-calculation-原因バイ不正確なデータ・タイプの使用/ 45960231#45960231(:)は2日前に尋ねました) –

関連する問題