2013-11-27 69 views
6

我必須使用'%'和雙數字,但在C++中它不起作用。 例子:錯誤C2296:'%':非法,左邊的操作數在C++中有'double'類型

double x; 
temp = x%10; 

我得到這個錯誤:

error C2296: '%' : illegal, left operand has type 'double' 

我怎麼能解決這個問題,而從雙轉換數字爲整數? 如果我轉換它,我會失去小數部分,我不想要。

有沒有其他的選擇?

+2

'%'操作符沒有爲'double'定義。你可以做'int%anotherInt'。嘗試['fmod'](http://en.cppreference.com/w/cpp/numeric/math/fmod) – Maroun

+0

通過應用%加倍,您期望得到什麼結果? –

+2

與餘數的劃分只對整數除法有意義。 '53.0/10 == 5.3',所以沒有剩餘部分用於'double'分割。 – MSalters

回答

14

%沒有爲雙打限定,但可以使用fmod代替:

Compute remainder of division Returns the floating-point remainder of numer/denom (rounded towards zero):

實施例(適於C++)從http://www.cplusplus.com/reference/cmath/fmod/

#include <cmath>  /* fmod */ 
#include <iostream> 

int main() 
{ 
    std::cout << "fmod of 5.3/2 is " << std::fmod (5.3, 2) << std::endl; 
    return 0; 
} 
+0

我有類似的麻煩,但你的建議不適用於我的。這是因爲在C:\ Program Files(x86)\ Windows Kits \ 8.0 \ Include \ um \ winbase.h(1999)發生的問題:它是Microsoft文件。更新它是不可行的。除了這種方式以外,還有什麼辦法可以克服這個麻煩? –

3

使用fmod功能

#include <math.h> 

double x; 
temp = fmod(x, 10.0); 
+1

'#include ',可能是因爲這是C++和'std :: fmod'。 – creichen

相關問題