else和if语句

0 c++ if-statement runtime

世界!

我目前正在自学C++.我正在阅读校长和使用C++练习,在为其中一个练习编写程序时,我对一个我没想到的程序的结果感到好奇.如果有人能解释为什么这会很好

源代码如下:

#include<iostream>

using namespace std;

int main()
{
    double val1 = 0;
    double val2 = 0;

    cout << "Enter two floating point values: ";
    cin >> val1 >> val2;

    cout << val1 + val2 << '\n'
         << val1 * val2 << '\n'
         << val1 / val2 << '\n';

    if(val1 > val2)
    {
        cout << val1 << " greater \n";
        cout << val2 << " lesser \n";
    }

    if(val1 == val2)
    {
        cout << val1 << " equals other floating point value \n";
        cout << val2 << "equals other floating point value \n";
    }

    else
    {
        cout << val2 << " greater \n";
        cout << val1 << " lesser \n";
    }

    system("PAUSE");
}
Run Code Online (Sandbox Code Playgroud)

当我输入类似6.9和5.4的内容时,它会给我输出:

6.9较大5.3较小

5.3更大6.9更小

我已经通过将else语句更改为if语句来解决了这个问题,但有人可以告诉我为什么在使用else语句时它会给出这个输出.谢谢!

tao*_*ocp 6

您的代码应如下所示:

if(val1 > val2)
{
    cout << val1 << " greater \n";
    cout << val2 << " lesser \n";
}

else if(val1 == val2)
{ //^^you missed this else

    cout << val1 << " equals other floating point value \n";
    cout << val2 << "equals other floating point value \n";
}

else
{
    cout << val2 << " greater \n";
    cout << val1 << " lesser \n";
}
Run Code Online (Sandbox Code Playgroud)

如果你错过了,那么逻辑非常明确else.具体来说,它将执行第一个if块.else如果没有那个,那就去吧else.