#include <iostream>
#include <cmath>
using namespace std;
int main(){
int a , b , c , D ;
double x1 , x2 ;
cout << " a = " ;
cin >> a;
cout << " b = " ;
cin >> b;
cout << " c = " ;
cin >>c;
D = pow(b,2) - 4 * a * c;
x1 = (-b + D ) / (2*a);
x2 = (- b - D) / (2*a);
cout << "D = " << D << endl;
D >= 0 ? ( x1,x2) : (cout << "nope . \n" , x1 = x2 = 0);
cout << x1 << endl;
cout << x2 << endl;
(D % 2) == 1 ? (D++) : (cout << "Number is even . \n" ); //check if number is uneven and if it is then add 1
cout << D << endl;
return 0;
}
将错误:operands抛出到?:具有不同类型'int'和'std :: basic_ostream'。 在注释所在的行。 是否可以使用条件运算符(?)进行修复?
答案 0 :(得分:6)
如注释中所建议,将两个操作数都强制转换为void
:
(D % 2) == 1 ? void(D++) : void(cout << "Number is even . \n" );
或更妙的是,使用常规的if
:
if (D % 2 == 1)
D++;
else
cout << "Number is even . \n";
对于其他? :
的使用,您也需要做同样的事情。
答案 1 :(得分:2)
已经在问题的评论中说过,但需要对此进行澄清。
如果这些分支不返回相同的类型,则ternary(?)运算符的返回类型等于两个代码分支的类型,则编译器将显示此错误。
对三元运算符的注释是根据条件为变量赋值:
bool isConnected = true;
static int idCount = 0;
int connectionID = isConnected ? ++idCount : -1;