在if-else循环中输入错误

时间:2017-04-21 05:36:35

标签: c++ if-statement input

我是c ++的新手并且正在编写“使用c ++编写原理和练习”一书

我被要求编写一个程序,将3种货币转换成美元。我已经编写了该程序,它可以完美地用于2种货币,但它不适用于第三种(欧元),我不知道为什么。

我确信这是一件非常简单的事情,我很想念,但我会很乐意帮助你!也欢迎任何对我的代码的批评。

#include <iostream>
using namespace std;

int main(){

constexpr double yen_to_dollars=0.0091;
constexpr double euro_to_dollars=1.071;
constexpr double pound_to_dollars=1.279;

double amount=1;
char currency =' ';

cout<<"please enter an amount of currency to be converted to dollars (Y, E or P):\n";
cin >> amount >> currency;


if(currency=='Y')
cout<<amount<<"Yen = " << yen_to_dollars*amount << "dollars\n";
else if(currency=='P')
cout<<amount<<"Pounds = "<<pound_to_dollars*amount << "dollars\n";
else if(currency='E')
cout<<amount<<"Euros = "<<euro_to_dollars*amount << "dollars\n";
else
cout<<"That is an invalid currency\n";

}

2 个答案:

答案 0 :(得分:0)

你不是在和E&#39; E&#39;正确地:else if(currency='E')&lt; - 这指定了&#39; E&#39;到currency变量而不是比较它。

以下是固定的例子:

#include <iostream>
using namespace std;

int main(){

constexpr double yen_to_dollars=0.0091;
constexpr double euro_to_dollars=1.071;
constexpr double pound_to_dollars=1.279;

double amount=1;
char currency =' ';

cout<<"please enter an amount of currency to be converted to dollars (Y, E or P):\n";
cin >> amount >> currency;


if(currency=='Y')
cout<<amount<<"Yen = " << yen_to_dollars*amount << "dollars\n";
else if(currency=='P')
cout<<amount<<"Pounds = "<<pound_to_dollars*amount << "dollars\n";
else if(currency=='E') // < -- fixed
cout<<amount<<"Euros = "<<euro_to_dollars*amount << "dollars\n";
else
cout<<"That is an invalid currency\n";

}

不确定它是否是stackoverflow的事情,但你应该尝试很好地格式化你的代码,所以说清楚。这会好一点:

#include <iostream>
using namespace std;

int main()
{
    const double yen_to_dollars = 0.0091;
    const double euro_to_dollars = 1.071;
    const double pound_to_dollars = 1.279;

    double amount = 1;
    char currency;

    cout << "please enter an amount of currency to be converted to dollars (Y, E or P):\n";
    cin >> amount >> currency;


    if (currency == 'Y')
        cout << amount << "Yen = " << yen_to_dollars*amount << "dollars\n";
    else if (currency == 'P')
        cout << amount << "Pounds = " << pound_to_dollars*amount << "dollars\n";
    else if (currency == 'E') // < -- fixed
        cout << amount << "Euros = " << euro_to_dollars*amount << "dollars\n";
    else
        cout << "That is an invalid currency\n";
}

答案 1 :(得分:0)

else if(currency = 'E') 'E'分配给currency

比较使用==和前两种情况一样:

else if(currency == 'E')

提示:

每当进行比较时,将rvalue(如果有的话)放在比较运算符的左侧。然后,如果您错误地为=键入==,编译器会抱怨并让您的生活更轻松。