2015-04-02 240 views
0

我试图在.5中除数,如果数字除以.5而我的余数为0,数字将上升到下一个。但是,如果没有,它会下降到下一个。语义问题对二进制表达式的操作数无效('double'和'double')

当我试图做到这一点时,我得到了一个问题,有人可以帮助我。

感谢

// 
// main.cpp 
// Promedio 
// 
// Created by Oscar Espinosa on 3/27/15. 
// Copyright (c) 2015 IPN ESIME Ticoman. All rights reserved. 
// 

#include <iostream> 
#include <cmath> 

using namespace std; 

int main() 
{ 
int ed, cv, qa, em, h, poo; 
float prom, red; 
string nom, ape; 

cout << " Introduce tus datos" << endl 
    <<"Nombre: "; 
getline(cin, nom); 
cout << "Apellidos: "; 
getline(cin, ape); 
cout << "Introduce las siguientes calificaciones" << endl 
    << "Ecuaciones Diferenciales: "; 
cin >> ed ; 
cout << "Calculo vectorial: "; 
cin >> cv ; 
cout << "Quimica apilcada: "; 
cin >> qa ; 
cout << "Electricidad y magnetismo: "; 
cin >> em; 
cout << "Humanidades II: "; 
cin >> h; 
cout << "Programacion orientada a objetos: "; 
cin >> poo ; 
prom = (ed+cv+qa+em+h+poo)/6.00; 

if (prom%.5 == 0) // Semantic issue invalid operands to binary expression ('double' and 'double') 
{ 
    ceil(prom); 
    red = ceil(prom); 
} 
else 
{ 
    floor(prom); 
    red = floor(prom); 
} 

cout << nom << " " << ape << " tu promedio es " << prom << " y se redondea a " << red; 

return 0; 
} 

回答

0

的问题是很清楚的:你不是if(var==0)之前定义var。在C++中,您需要在第一次使用之前定义变量。注意编译器告诉你什么。在G ++的情况:

error: 'var' was not declared in this scope 

,我认为这是非常明确的!

PS:不要在答案后修改代码,因为最终会混淆每个人。在实际的代码中,你传递0.5作为模数运算符参数。该运营商需要int。您需要其他方式测试float是否为0.5的倍数。特别是,您还应该注意舍入误差。

提示:a floatx是当且仅当是整数时为0.5的倍数。因此2*x - floor(2*x)必须接近零,即abs(2*x - floor(2*x)) < 1e-12以避免浮点错误。

见相关的问题:Checking if float is an integer

+0

的代码是错误的,当我将它张贴,我已经编辑它。 – 2015-04-02 18:58:02

4

@Oscar埃斯皮诺萨
你不能使用%(模)运算符与双重价值
因此,它显示了错误的表达无效操作数..
尝试使用fmod(x,y) function..it会工作

+0

优秀的答案,不知道这个函数,upvoted :)但是,再次,测试相等到零小到一些小epsilon。 – vsoftco 2015-04-02 19:05:03

1

模数(%)只能与整数值一起使用。 您可以使用FMOD,但如果你的意思是整数值工作,也许这样的技巧可以帮助:

if (10*static_cast<int>(prom)%5 == 0) 
相关问题