简体   繁体   English

如预期,IF声明

[英]While expected, IF Statement

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);
    }

I have no clue why but Visual Studio 12 is bringing an error on the else saying that it expects a while. 我不知道为什么,但是Visual Studio 12在其他地方带来了错误,说它需要一段时间。 I've done many if else statements before and also in this program that work fine so could anyone help me to understand why in this case it is not happy? 我已经做了很多的if else语句之前,并且在这种程序,做工精细,以便任何人都可以帮助我理解为什么在这种情况下,它是不幸福吗?

The correct syntax is: 正确的语法是:

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

when using if and 当使用if

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

when using do...while . 当使用do...while

There's no if() do statement in C/C++! C / C ++中没有if() do语句!

You have a do after the if , so the compiler expects a while after the do block. if之后有一个do ,因此编译器希望在do块之后有一段while

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

or 要么

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

dont use do. 不要使用。 that is for a while loop and the correct syntax for using that is 那是一个while循环,使用它的正确语法是

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

what you want is 你想要的是

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);
}

Because you are doing it wrong! 因为你做错了! C++ has if-else statements and do-while statements. C ++具有if-else语句和do-while语句。 do expects a while following itself, meanwhile while can be used independently. do期望有一段while跟随自己,同时while可以独立使用。 Similarly, if can be used independently, but else expects an if before itself. 类似地, if可以独立使用,但是else期望if本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM