【问题标题】:While expected, IF Statement正如预期的那样,IF 声明
【发布时间】:2013-12-09 04:43:46
【问题描述】:
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 会在 else 上出现错误,说它需要一段时间。我之前做过很多 if else 语句,并且在这个程序中运行良好,所以任何人都可以帮助我理解为什么在这种情况下它不开心吗?

【问题讨论】:

  • 谁教你这样使用do
  • 这是因为第一行末尾的do。要么删除它,要么添加 while 以配合它。
  • 天哪,我现在感觉自己像个白痴!感谢您指出这一点!
  • 追加0x499602D2的问题:谁教你写if(cond) doreturn(0)system("pause")

标签: c++ if-statement while-loop


【解决方案1】:

正确的语法是:

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

当使用if

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

使用do...while时。

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

【讨论】:

  • 愚蠢的错误可能发生在任何人身上,我猜。 :)
【解决方案2】:

if 后面有一个do,因此编译器期望在do 块后面有一个while

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

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

【讨论】:

    【解决方案3】:

    不要使用do。那是一个while循环,使用它的正确语法是

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

    【讨论】:

      【解决方案4】:

      因为你做错了! C++ 有 if-else 语句和 do-while 语句。 do 期望 while 跟随自己,同时 while 可以独立使用。 类似地,if 可以独立使用,但 else 需要在其前面加上 if

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-09
        • 2018-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多