[英]Invalid operands of types 'double' and 'const char [2]' to binary 'operator!='|
I have a program that I need to make it so if I enter my first number as x it will terminate but i can't do that because my num1 is a double. 我有一个程序需要这样做,所以如果我输入第一个数字x,它将终止,但我不能这样做,因为num1是双精度型。 If anyone could help me figure out how to do that, that would be great.
如果有人可以帮助我弄清楚该怎么做,那就太好了。 Thanks
谢谢
#include <iostream>
using namespace std;
void compute(double, double);
int main()
{
double num1, num2;
while (num1!="x")
{
cout << "Enter First Number: " << endl;
cin >> num1;
cout << "Enter Second Number: " << endl;
cin >> num2;
compute(num1, num2);
}
return 0;
}
void compute(double num1, double num2)
{
double sum,diff,prod,quotient;
cout << "First Number: " << num1 << endl;
cout << "Second Number: " << num2 << endl;
sum=num1+num2;
diff=num1-num2;
prod=num1*num2;
quotient=num1/num2;
cout << "Sum: " << sum << endl;
cout << "Difference: " << diff << endl;
cout << "Product: " << prod << endl;
cout << "Quotient" << quotient << endl;
}
Your main problem here is that you're comparing a number to a const char*
(ie, a string literal). 您的主要问题在于,您正在将数字与
const char*
(即字符串文字)进行比较。
If you want your program to compile, you might want to compare num1
to the character x
, for example num1 != 'x'
(not single quotes). 如果要编译程序,则可能需要将
num1
与字符x
进行比较,例如num1 != 'x'
(不是单引号)。 I will not guarantee this will work correctly, as comparing doubles and characters is a bit ludicrous, but it should compile and may get you a bit further down the road. 我不能保证它会正常工作,因为比较双打和字符有点荒谬,但是它应该可以编译,并且可能会让您走得更远。
You store your input in a std::string
and check the content of the string before converting it to a double
: 您将输入存储在
std::string
并在将字符串转换为double
之前检查std::string
的内容:
std::string s;
std::cout >> s;
if (s == "x")
{
// do something
}
else
{
std::stringstream ss(s);
double num1;
ss >> num1;
// do something else
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.