在预期中,IF 语句

While expected, IF Statement

本文关键字:IF 语句      更新时间:2023-10-16
if (Mileage > 0) do
    {
        calculateMileage();
        cout << "The cost of shipment over " << setprecision(2) << Mileage << " miles is 234" << variableShippingCost << ".";
        cout << "n n";
        system("pause"); //to hold the output screen
        return(0);
    }
    else
    {
        cout << "n ERROR: The distance should be a positive value.";
        system("pause"); //to hold the output screen
        return(0);
    }

我不知道为什么,但Visual Studio 12在其他地方带来了一个错误,说它需要一段时间。我之前做过很多语句,而且在这个程序中工作正常,所以谁能帮助我理解为什么在这种情况下它不高兴?

正确的语法是:

if (...) 
{...} else {...} 

使用if

do {...}
while (...);

使用do...while时。

C/C++ 中没有if() do语句!

你在if之后有一个do,所以编译器期望在do块之后有一个while

if (Mileage > 0)
{
    do
    {
        calculateMileage();
        //etc...
    } while (something);
}
else
{
    //etc...
}

if (Mileage > 0) // no `do` here
{
    calculateMileage();
    //etc...
}
else
{
    //etc...
}
不要

使用do.那是一段时间的循环,使用的正确语法是

do{
...code here...
} while(some condition is true)

你想要的是

if (Mileage > 0) //there is an implicit then here no need to do anything here
{
    calculateMileage();
    cout << "The cost of shipment over " << setprecision(2) << Mileage << " miles is 234" << variableShippingCost << ".";
    cout << "n n";
    system("pause"); //to hold the output screen
    return(0);
}   //<<<------if you really wanted to use the do (which you shouldnt) put a while here.
else
{
    cout << "n ERROR: The distance should be a positive value.";
    system("pause"); //to hold the output screen
    return(0);
}

因为你做错了!C++有 if-else 语句和 do-while 语句。 do期望while跟随自己,同时while可以独立使用。同样,if可以独立使用,但else期望先if