if-else循环找到解决方案

New*_*258 0 c++ loops if-statement

我的代码是:

#include<stdio.h>
void main(void)
{
    float timeLeavingTP;
    int transitNumber;
    float transitTime;
    printf("Please enter the time leaving TP.\n");
    scanf_s("%f",&timeLeavingTP);
    printf("Please enter bus number.\n");
    scanf_s("%d",&transitNumber);
    if(timeLeavingTP==1.00)
    {

        if(transitNumber==27)
        {
        transitTime=1.56;
        }
        else if(transitNumber==8);
        {
        transitTime=1.39;
        }
    }
    if(timeLeavingTP==6.30)
    {
        if(transitNumber==27)
        {
        transitTime=7.32;
        }
        else if(transitNumber==8)
        {
        transitTime=7.29;
        }
    printf("The time reached home is %f\n",transitTime);
    }
}
Run Code Online (Sandbox Code Playgroud)

经过调试我得到了

Please enter the time leaving TP
1.00
Please enter bus number
27
Please enter to continue...
Run Code Online (Sandbox Code Playgroud)

我的问题是如何调整程序使其看起来像下面的那个.我犯了什么样的错误?

Please enter the time leaving TP
1.00
Please enter bus number
27
The time reached home is 1.56
Run Code Online (Sandbox Code Playgroud)

我在这里先向您的帮助表示感谢!包括==后我们的调试仍然一样吗?还有别的我做错了吗?

Bil*_*nch 5

第1部分:=vs==

注意:

if(timeLeavingTP=1.00)
Run Code Online (Sandbox Code Playgroud)

不按你的意愿行事.它将timeLeavingTP指定为1.00.

你可能想要:

if(timeLeavingTP==1.00)
Run Code Online (Sandbox Code Playgroud)

此外,请注意您的程序中出现此错误6次.

第2部分:比较浮点数

在这种情况下,您的代码可能会起作用,但我不确定是否会这样做.通常很难直接比较2个浮点数,因为存储它们的不准确性(例如,0.1通常在浮点中无法表示).

大多数人通过以下几种方式解决这个问题:

  1. 测试数字周围的范围.
  2. 转换为某些修复宽度格式.也许您可以将数字存储为整数,知道它的表示实际上是0.01*存储的数字.
  3. 在这种情况下,您实际上可以将信息存储为字符串,并进行比较.

第3部分:条件

要编写适当的条件,它应该看起来像:

if (condition) {
    ...
} else if (condition) {
    ...
} else if (condition) {
    ...
} else {
    ...
}
Run Code Online (Sandbox Code Playgroud)

你当然可以嵌套条件:

if (condition) {
    if (condition) {
        ...
    } else {
        ...
    }
} else if (condition) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

例如,当您执行以下操作时,您的代码会混淆:

    } 
    else(transitNumber=8);
    {
        transitTime=1.39;
    }
Run Code Online (Sandbox Code Playgroud)

请注意,else语句之后不接受条件.

第4部分:过多的分号

另外,请注意在else和if语句之后没有分号.分号仅出现在大括号内.所以这句话:

if(timeLeavingTP=6.30);
Run Code Online (Sandbox Code Playgroud)

虽然在语义上有效,但没有达到预期效果.你真的想删除那个分号.