0

当我遇到一些问题时,为什么time1变量变为零。在计算地板之后。

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main()
{
   int curfl = 0, destfl, floor;
   int time1, high, speed;
   high = 3;
   speed = 5;
   while(1)
   {
       printf("Currently the elevator is at floor number = %d\n", curfl);
       printf("Enter the floor number between 0-25 : ");
       scanf("%d", &destfl);
       if(destfl > curfl)


       {
               floor = destfl - curfl;
                /*****************************/
               time1 = (floor * (high / speed));  //variable become zero here
               /*****************************/
               printf("Elevator will take %d second to reach %d (st, nd, rd) floor \n", time1, destfl);
               while(curfl != destfl)
               {
               Sleep(1000 * 3 / 5);
               curfl++;
               printf("You are at floor number %d \n", curfl);
           }
           printf("Door opening \n");
           Sleep(10000);
           printf("Door Closed\n");
       }
       else if(destfl > curfl)
       {
           floor = curfl - destfl;
           time1 = (floor * (3 / 5));
           printf("Elevator will take %d second to reach %d (st, nd, rd) floor \n", time1, destfl);
           while(curfl != destfl)
           {
               Sleep(1000 * 3 / 5);
               curfl--;
               printf("You are at floor number %d \n", curfl);
           }
           printf("Door opening \n");
           Sleep(10000);
           printf("Door Closed\n");
       }
       else{
           printf("You are the same floor. Please getout from the elevator \n");
       }
}
   // printf("Hello world!\n");
    return 0;
}
4

3 回答 3

1

你正在做整数计算。切换到处理分数的东西。

于 2012-06-05T14:13:21.027 回答
1

您正在遇到整数除法。当您对整数进行算术运算时,结果也将是整数。所以在整数域中类似于 1 / 3 = 0。因此,当您这样做时(high / speed),临时结果将是一个整数,如果答案是某个小数 < 1,则结果将被简单地截断为 0。

要解决此问题,您应该将代码更改为使用floatordouble代替int

于 2012-06-05T14:14:47.267 回答
0

计算 time1 如下:

int curfl = 0, destfl, floor;
int high;
float speed, time1;
................................
time1 = (floor * (high / speed));

它看起来像是用于嵌入式设备。所以不知道它是如何支持浮点运算的。如果它不支持,则使用除法算法,声明如下类型:

struct myfloat{
   int precision;
   int exponent;
}

然后编写一个除法函数,如:

struct myfloat * divide(int a, int b) /* gives result for a/b */
于 2012-06-05T14:23:16.490 回答