写一段控制电梯升降的代码
这里给出一个简单的控制电梯升降的代码示例:
#include <stdio.h>
int main()
{
int current_floor = 1; // 当前所在楼层
int target_floor; // 目标楼层
int direction = 1; // 电梯运行方向,1表示上行,-1表示下行
while (1) {
// 读取目标楼层
printf("请输入目标楼层:");
scanf("%d", &target_floor);
// 判断电梯运行方向
if (target_floor > current_floor) {
direction = 1;
} else if (target_floor < current_floor) {
direction = -1;
} else {
printf("已到达目标楼层%d\n", current_floor);
continue;
}
// 电梯运行直到到达目标楼层
while (current_floor != target_floor) {
current_floor += direction;
printf("电梯正在前往%d楼\n", current_floor);
}
// 到达目标楼层,停止电梯
printf("电梯已到达%d楼\n", current_floor);
}
return 0;
}
这个代码使用了一个while循环来不断读取用户输入的目标楼层,并判断电梯运行方向,然后使用另一个while循环来让电梯运行直到到达目标楼层。在运行过程中,会输出一些提示信息,让用户知道电梯的运行状态。当电梯到达目标楼层时,会输出一条到达目标楼层的提示信息。
原文地址: http://www.cveoy.top/t/topic/Jrl 著作权归作者所有。请勿转载和采集!