2012-02-14 229 views
14

編譯我收到以下錯誤類型的無效操作數int和double二進制「操作符%」

invalid operands of types int and double to binary 'operator%' at line 
"newnum1 = two % (double)10.0;" 

程序後,爲什麼會這樣呢?

#include<iostream> 
#include<math> 
using namespace std; 
int main() 
{ 
    int num; 
    double two = 1; 
    double newnum, newnum1; 
    newnum = newnum1 = 0; 
    for(num = 1; num <= 50; num++) 
    { 

     two = two * 2; 
    } 
    newnum1 = two % (double)10.0; 
    newnum = newnum + newnum1; 
    cout << two << "\n"; 
    return 0; 
} 
+1

'(double)10.0'這個類型轉換不做任何事情。 10.0已經是雙重類型。 10.0f是浮點類型,10是(帶符號)整數類型。 – Lundin 2012-02-14 14:33:40

+0

@Lundin:'10'具體是'int'類型,而不是任何任意有符號整數類型。 – 2016-01-07 19:32:41

回答

33

因爲%只定義爲整數類型。這就是模數運算符。

標準的5.6.2:

的操作數*和/應有算術或枚舉類型; %的操作數應具有整數或枚舉類型。 [...]

正如Oli指出的那樣,您可以使用fmod()。不要忘記包括math.h

+0

用法:包含'math.h',然後使用'fmod(15,2);'。更多內容參見['fmod'文檔](http://www.cplusplus.com/reference/cmath/fmod/)。 – Matt 2014-03-20 23:32:10

17

因爲%只適用於整數類型。也許你想用fmod()

1

是的。 %運算符沒有爲double類型定義。按位運算符也是如此,如「&,^,|,〜,< <,>>」。

相關問題