c++怎么用if语句判断两个字符是否相等

#include<iostream>
using namespace std;
int main()
{
int weight;
char exp;
cin >> weight >> exp;
double postage=0;
if ( 'exp' == 'n' )
postage = 0;
else
postage = 2.0;
postage = postage + 0.8 + 0.5 * ( weight - 1 );
cout << postage << endl;
return 0;
}
用户输入:邮件的重量,以及是否加快
计算规则:重量在1克以内(包括1克),
基本费0.8元。超过1克的部分,按照0.5元/克的比例加收超重费。如果用户选择加快,多收2元。
这个程序错在哪儿

1. 判断两个字符是否相等

char a = 'a';
char b = 'b';
if (a == b) {
    cout<<"a, b相等";
} else {
    cout<<"a, b 不相等";
}

2. 判断两个字符串是否相等

char * str1, *str2;
str1 = "Hello";
str2 = "Hello";
if(0 == strcmp(str1, str2)) {
    cout<<"str1 与 str2 内容相同"<<endl;
} else {
    cout<<"str1与 str2 内容不相同";
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-27
1、错在“postage = postage + 0.8 + 0.5 * ( weight - 1 );”,应该改成:
if (weight <= 1)
postage = postage + 0.8;
else
postage = postage + 0.8 + 0.5 * ( weight - 1 );
2、还有if ( 'exp' == 'n' ) 这个错了,应该为if ( 'n' == exp )
3、#include<iostream>改成#include <iostream>(中间有空格)
4、还有严谨的说要这样:int main()改为int main(void)
第2个回答  2015-10-26
可以直接用strcmp函数来判断吧。比如if(!strcmp(str1,str2))

如果相等的话,则返回,如果不想等,则结束这个if语句
第3个回答  2013-09-27
if ( 'exp' == 'n' )
变量名字不用引号。
而且我建议写成 if('n'==exp)
这样防止少写一个等号。
第4个回答  2013-09-27
#include<iostream>
using namespace std;
int main()
{
int weight;
char exp;
cin >> weight >> exp;
double postage=0;
if ( exp == 'n' )//////////////////这样
postage = 0;
else
postage = 2.0;
postage = postage + 0.8 + 0.5 * ( weight - 1 );
cout << postage << endl;
return 0;
}本回答被提问者采纳
相似回答