2010-11-02 77 views
1

我有下面的代碼有問題:以整數計算和使用浮點數的C/C++

#include <stdio.h> 
#include <iostream> 

int main() 
{ 
int a, b; 

printf("Please type in your number a: "); 
scanf_s("%d", &a); 

printf("Please type in your number b: "); 
scanf_s("%d", &b); 

printf("Solution 1 (divide and modulus): %f\n", a/b + a % b); 
printf("Solution 2 (cast): %f", (float) a/b); 

std::cin.get(); 
std::cin.get(); 

return 0; 

} 

我想我的程序讀取兩個整數,我想用兩種不同的方法對他們沒有分裂舍入錯誤。第一種解決方案不起作用。輸出只是零。我不知道問題出在哪裏。

+1

你是什麼輸入? – 2010-11-02 12:52:32

+1

除了您的問題已經得到充分解決,我不知道爲什麼你使用。嘗試在風格上保持一致,給予後者更多的選擇。恕我直言:) – 2010-11-02 13:01:21

+0

甚至使用'stdio.h'而不是正確的'cstdio' – 2010-11-02 13:06:30

回答

2

a/b + a%b結果是integer%d),但你打印出一個float%f)。

+0

是的。現在我明白我的錯誤在哪裏了。謝謝。 – Ordo 2010-11-03 05:46:11

1

你應該改變

printf("Solution 1 (divide and modulus): %f\n", a/b + a % b); 

printf("Solution 1 divide %i modulus %i \n", a/b, a % b); 
2

我覺得應該是:

a/b + (a%b)/(float)b 
+0

使用float類型轉換任何變量將導致所有變量爲float n輸出將是float,而不是int。 – letsc 2010-11-02 18:05:15

+0

是的,但是因爲他正在打印一個浮動(%f)我雖然他的公式可能是錯的。 – George 2010-11-02 19:21:53