2017-08-31 105 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); 

如果你運行這段代碼,你會意識到, exponent_result的輸出使用pow() function計算,總是從中減去1。例如,如果exponent_result應該是5^3的結果,那麼結果將是124而不是125

我在做什麼錯?

Fyi,我在我的文件開頭有這個。

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

你檢查了你的問題。當我試圖運行你的程序時,它工作正常。沒有任何問題。如果您仍有問題,請在線共享可運行代碼,以便我們檢查問題。我得到了正確的輸出。你想說輸入的東西有什麼問題嗎? –

+0

不要嘗試將浮點數用於整數計算。整數總是精確的,花車幾乎總是沒有。 I –

+1

避免截斷,取而代之'exponent_result = lround(pow(add2,exponent));' – chux

回答

7

pow評估浮點運算,並可能爲pow(x, y) = exp(y * log(x))實現。

這可能會導致結果爲「熄滅」:你可能得到的只是害羞的125值,這是截斷爲124時,從powdouble返回類型轉換回int

最簡單的補救措施是爲積分參數構建您自己的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天前:)) –

相關問題