在c 下面的這段代碼中,顯示了一個錯誤:
expression must have integral or unscoped enum type
illegal left operand has type 'double'
是否可以在不需要使用的情況下糾正它fmod?
# include <iostream>
using namespace std;
int main()
{
int x = 5, y = 6, z = 4;
float w = 3.5, c;
c = (y w - 0.5) % x * y; // here is the error
cout << "c = " << c << endl;
return 0;
}
uj5u.com熱心網友回復:
您可以使用型別轉換來修復它:
c = ((int) (y w - 0.5)) % x * y;
為了澄清您在評論中的回答,更改c為 typeint仍然不起作用,因為該部分(y w - 0.5)未被評估int為double。并且模數運算不將該型別作為引數。
完整修改代碼:
#include <iostream>
using namespace std;
int main()
{
int x = 5, y = 6, z = 4;
float w = 3.5, c; //c could still stayed as float
c = ((int) (y w - 0.5)) % x * y; //swapped out here
cout << "c = " << c << endl;
}
輸出:c = 24。
在這里要清楚,這只是針對這種情況的臨時修復,當您知道(y w - 0.5)將有一個明確的整數值時。如果該值類似于0.5或1.447,std::fmod則是可取的。
這是關于float/double和之間互動的運算式中的型別轉換規則的帖子int/long long:C 運算子中的隱式型別轉換規則
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/364654.html
