【问题标题】:2 identical codes, get error at one2个相同的代码,一个得到错误
【发布时间】:2016-01-15 15:41:31
【问题描述】:

我在代码中添加了 cmets,我有编译器问题吗?我想不通,我试着在谷歌和书上看,但我不明白为什么前半部分代码只接受数字和单位之间有空格的输入,而第二个代码同时接受数字和单位。

我正在使用代码块。到目前为止,我尝试关闭它并再次打开它。

int main(){

    constexpr double dollar_to_euro = 0.91;
    constexpr double dollar_to_yen = 117.07;
    constexpr double dollar_to_pounds = 0.70;
    double sum = 1;

    char curr = '\0'; // tried replacing '\0' with '0' and ' ' 

    cout << "Please enter sum, followed by currency for conversion.\n"
         << "U for dollar, E for euro, Y for yen and P for pounds.\n";

    cin >> sum >> curr; // This is my issue, it does not want to accept "sumcurr" together, it only accepts it if theres space in between 
                        // yet on the second code for inches or centimeters it does accept them being together. Look down.
                        // For example entering "5 E" works, yet "5E" does not work. 
    if(curr=='E')
        cout << "The amount " << sum << " euro is " << sum/dollar_to_euro << " dollars\n";

    else
        cout << "GOD DAMMIT !!!!\n";


    constexpr double cm_per_inch = 2.54;

    double len = 1;

    char unit = '\0';
    cout << "Please enter length followed by unit.\n";

    cin >> len >> unit; // Over here it works, this is an example from a book. Entering "5i" works. 

    if(unit=='i')
        cout << len << " in == " << cm_per_inch*len << "cm.\n";
    else
        cout << "Wrong input !\n";
}

【问题讨论】:

  • 单位输入“5E”有效吗?
  • 查看可选“e”或“E”部分:en.cppreference.com/w/cpp/language/floating_literal
  • 5E 不起作用,只有 5E 起作用。但是第二个代码 5i 有效。对我来说它们是相同的,我无法理解为什么一个有效而另一个无效。
  • 尤里卡!!!我现在明白了,非常感谢!我试图弄清楚一段时间。
  • 一种更安全的方法是为美元、欧元和英镑定义适当的类,并由用户定义您自己的文字 _U_E_P

标签: c++ char cin


【解决方案1】:

这里的问题是 E/e 在浮点数中有效,但 5E/5e 不是有效的浮点数,因为您需要在 E/@987654327 之后的值@。因此,当您输入 5e 时,sum 的输入将失败,因为 5e0 可以使用的语法无效。如果您使用 E/e 以外的任何其他内容,那么它将像您的第二个示例一样工作。

有关浮点数格式的更多信息,请参阅:Cppreference floating point literal

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    相关资源
    最近更新 更多