2012-08-23 33 views
0

我是C++新手,这就像我的第一个程序,我使用Visual C++ 2010 Express。 这是一个重量转换的东西。有一个if循环,一个else if循环和一个else。 下面是代码:为什么我的程序停留在if循环中?

#include <iostream> 

using namespace std; 

int main() { 
float ay,bee; 
char char1; 
cout << "Welcome to the Ounce To Gram Converter" << endl << "Would you like to convert [O]unces To Grams or [G]rams To Ounces?" << endl; 
start: 
cin >> char1; 

if (char1 = "G" ||"g"){ 
cout << "How many grams would you like to convert?" << endl; 
cin >> bee; 
cout << bee << " grams is equal to: " << bee*0.035274 << " ounces." << endl; goto start; 
} 

else if (char1 = "o"||"O"){ 
cout << "How many ounces would you like to convert" << endl; 
cin >> ay; 
cout << ay << " ounces is equal to: " << ay/0.035274 << " grams." << endl; goto start; 
} 

else{ 
    cout << "Error 365457 The character you entered is to retarded to comprehend" << endl; 
goto start; 
} 

cin.ignore(); 
cin.get(); 
return 0; 
    } 

如果我进入一个 “G”,则执行此:

if (char1 = "G" ||"g"){ 
cout << "How many grams would you like to convert?" << endl; 
cin >> bee; 
cout << bee << " grams is equal to: " << bee*0.035274 << " ounces." << endl; goto start; 
} 

像它应该

但是,如果我输入一个 “O”,它执行该:

if (char1 = "G" ||"g"){ 
cout << "How many grams would you like to convert?" << endl; 
cin >> bee; 
cout << bee << " grams is equal to: " << bee*0.035274 << " ounces." << endl; goto start; 
} 

取而代之的是:

else if (char1 = "o"||"O"){ 
cout << "How many ounces would you like to convert" << endl; 
cin >> ay; 
cout << ay << " ounces is equal to: " << ay/0.035274 << " grams." << endl; goto start; 
} 

即使我把东西乱,如 “H” 发生这种情况:

if (char1 = "G" ||"g"){ 
cout << "How many grams would you like to convert?" << endl; 
cin >> bee; 
cout << bee << " grams is equal to: " << bee*0.035274 << " ounces." << endl; goto start; 
} 

取而代之的是:

else{ 
    cout << "Error 365457 The character you entered is to retarded to comprehend" << endl; 
goto start; 
} 

请告诉我,我做错了什么。

+1

有什么具体的原因,你正在使用'goto'?你应该真的考虑使用一个实际的循环('for'或'while')。 –

回答

3

char1 = "o"||"O"将始终评估为真,因为"O"不为空。

你想使用char1 == 'o' || char == 'O'和类似的所有你的if语句。

请注意,=是赋值,==是相等性检查。分配时测试时使用==,分配时使用=。 C和C++允许您在检查中使用=,该检查返回赋值的值。这个值不是0,它的计算结果为true,因此你的if语句执行。

+0

我确实将它更改为char1 == o || char1 == O,并且所有这些都类似于Forr,但我在等号之下出现错误。它表示操作数类型不兼容(“char”和const char *) –

+0

使用单引号不是双引号 – Dervall

相关问题