0

我是 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;
}

请告诉我我做错了什么。

4

1 回答 1

3

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

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

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

于 2012-08-23T11:21:33.740 回答