为什么我的程序卡在if循环中?

时间:2012-08-23 11:18:20

标签: visual-c++

我是C ++的新手,这就像我制作的第一个程序,我使用的是Visual C ++ 2010 Express。 这是一种重量转换的东西。有一个if循环,一个else if循环和一个else。 这是代码:

#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 个答案:

答案 0 :(得分:3)

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

您希望在if语句中使用char1 == 'o' || char == 'O'和类似内容。

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