c++ - 错误 : operands to ?:具有不同的类型 'int' 和 'std::basic_ostream<char>'

标签 c++

#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 to ?: have different types 'int' and 'std::basic_ostream' 。 在注释所在的行。 是否可以使用条件运算符 (?) 来修复它?

最佳答案

按照评论中的建议,将两个操作数都转换为 void:

(D % 2) == 1 ? void(D++) : void(cout << "Number is even . \n" );

或者更好的是,使用常规的 if:

if (D % 2 == 1)
    D++;
else
    cout << "Number is even . \n";

您需要为 的其他用途做同样的事情吗? : 也是。

关于c++ - 错误 : operands to ?:具有不同的类型 'int' 和 'std::basic_ostream<char>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55228024/

相关文章:

c++ - 数组迭代器不可取消引用错误

C++ REST (Casablanca) - web::json::value 没有名为 'field_map' 的成员

C++:线程竞争条件是否会破坏每字节级别的静态/全局整数值?

c++ - 关于 C++ 中的 sleep 命令

c++ - 另一个 "OpenGL Not Drawing"问题

c++ - C++中的析构函数

c++ - 无法编译 boost::asio::basic_datagram_socket<boost::asio::ip::udp>::basic_datagram_socket()

c++ - 将指向项目的指针存储在 std::set 中是否安全?

c++ - 去除连通图中的边的算法

c++ - 在 DCMTK 中将 OFString 转换为字符串或字符