C++无法将字符变量与值进行比较
我第一次上cs课就得这么做。这是一个基本的计算器,它接受一个运算符和一个值,并计算从0开始的总数C++无法将字符变量与值进行比较,c++,char,comparison,C++,Char,Comparison,我第一次上cs课就得这么做。这是一个基本的计算器,它接受一个运算符和一个值,并计算从0开始的总数 #include <iostream> using namespace std; int main() { char oprtr; float value, total = 0.0; cin >> oprtr >> value; while (oprtr != "q") { if (oprtr ==
#include <iostream>
using namespace std;
int main()
{
char oprtr;
float value, total = 0.0;
cin >> oprtr >> value;
while (oprtr != "q")
{
if (oprtr == "+")
total += value;
else if (oprtr == "-")
total -= value;
}
}
它还没有完成,但已经有问题了。它给出了一些错误,比如将char值与int值进行比较时,双引号q表示字符串。单引号“q”表示字符
因此:
Char表示字符,必须使用单引号表示这些字符,双引号表示字符串
出现此错误的原因是,您试图将一个字符与一个字符串文字或常量字符进行比较,而得到的确切错误是:
操作数类型是不兼容的字符和常量字符
以下代码将修复此错误:
#include <iostream>
using namespace std;
int main()
{
char oprtr;
float value, total = 0.0;
cin >> oprtr >> value;
while (oprtr != 'q')
{
if (oprtr == '+')
total += value;
else if (oprtr == '-')
total -= value;
}
}
比较字符串长度是C编程中的一个常见函数,因为它允许您查看哪个字符串包含更多字符。这对于排序数据非常有用。比较字符串需要一个特殊的函数;不要使用!=或==
而且,由于您只读取一次语句或表达式,因此当字符不等于“q”时,您无需循环。您基本上应该执行一个操作。此外,switch是一个非常有用的结构,用于比较文本而不是几个if。因此,我将简化为
#include <iostream>
using namespace std;
int main(){
char op;
float value, total = 0.0;
cin >> op >> value;
//it is important at this stage to check for errors, as they are most likely
//to occur.
if(!cin){
cerr << "Error: format unknown! \n"; //basic error handled here, the prog outputs the error
}
//now perform the calculation
switch(op){
case '+': total += value;
break;
case '-' : total -= value;
break;
case 'q' : break; //i presume q is your quit character
default: /*unknown character*/ cerr << "Unknown operation! \n";
}
cout << "Total: "<<total << endl;
return 0;
}
这基本上是读入一个表达式并将其添加到总数中。您可以将其修改为任意长度。这并不能回答问题,请在回答之前进行研究。
#include <iostream>
using namespace std;
int main(){
char op;
float value, total = 0.0;
cin >> op >> value;
//it is important at this stage to check for errors, as they are most likely
//to occur.
if(!cin){
cerr << "Error: format unknown! \n"; //basic error handled here, the prog outputs the error
}
//now perform the calculation
switch(op){
case '+': total += value;
break;
case '-' : total -= value;
break;
case 'q' : break; //i presume q is your quit character
default: /*unknown character*/ cerr << "Unknown operation! \n";
}
cout << "Total: "<<total << endl;
return 0;
}