当我遇到一些问题时,为什么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;
}
答案 0 :(得分:1)
您正在进行整数计算。切换到处理分数的东西。
答案 1 :(得分:1)
您正在进行整数除法。对整数进行算术运算时,结果也是整数。所以像整数土地中的1/3 = 0。所以当你做(high / speed)
时,临时结果将是一个整数,如果答案是一些小数&lt; 1,结果将截断为0。
要解决此问题,您应该将代码更改为使用float
或double
代替int
。
答案 2 :(得分: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 */