#算法 c语言

该代码片段涉及计算电梯服务过程中,根据给定的正整数请求列表,从初始第6层出发,满足每个楼层停留5秒后到达,计算总耗时。原始代码存在问题,如未正确处理输入0的结束标志和停留时间,改进后的版本解决了这些问题。
摘要由CSDN通过智能技术生成

问题:我们城市最高的建筑只有一部电梯。请求列表由N个正数组成。这些数字表示电梯将按指定的顺序停在哪个楼层。电梯上升一层需要6秒,下降一层需要4秒。电梯在每站停留5秒钟。
对于给定的请求列表,您要计算完成列表上的请求所花费的总时间。电梯一开始在第6层,当要求被满足时不需要返回到第1层。
nput format:
有多个测试用例。每种情况包含一个正整数N,后面跟着N个正数。输入的所有数字都小于100。N=0的测试用例表示输入的结束。这个测试用例不被处理

 我的:

#include<stdio.h>
int main()
{
	int n = 0;
	int s = 0;

	while (scanf("%d", &n) != 0)
	{
		int a[100] ;
		for (int i = 0; i < n; i++)
		{
			scanf("%d", a + i);
			int k = 6;
			while (a[i] < k)
			{
				int c = k - a[i];
				s =s+ c * 4;
				k = a[i];
			}
			while (a[i] > k)
			{
				int c = a[i] - k;
				s = s + c * 6;
				k = a[i];
			}
		}
	}
	printf("%d\n", s);
	return 0;
}

 这是我自己

有以下问题

1题目要求的是输入0跳出

而我写的是判断scanf有没有接收到数字

2然后还忽略的题目里的停留时间5秒

3变量的位置问题

我的k,是在循环里定义的,也就是说,我对于k=层数的要求跟本就没有用上,每一次k都会等于6

这是gpt正确的

但是他没做到,我一组输入,然后回车是下一组输入而不是直接输出这一组的结果

#include <stdio.h>

int main() {
    int N;

    while (1) {
        // Input the number of floors
        scanf("%d", &N);

        // Check for the end of input
        if (N == 0) {
            break;
        }

        int total_time = 0;
        int current_floor = 0;

        // Process each floor request
        for (int i = 0; i < N; i++) {
            int floor;
            scanf("%d", &floor);

            // Calculate time to move to the requested floor
            int time_to_move = (floor > current_floor) ? 6 * (floor - current_floor) : 4 * (current_floor - floor);

            // Update the current floor and add the time spent
            current_floor = floor;
            total_time += time_to_move + 5; // 5 seconds for stopping at the floor
        }

        printf("%d\n", total_time);
    }

    return 0;
}

他的优点:

1用一个条件运算符,把我的两个while都省了

所以又让他进行了一个修正 

也没做到,但是我去试了一下pta通过了,可能是没法做到吧

布吉岛
这是让他在我的基础上改进的

#include<stdio.h>

int main() {
    int n = 0;
    
    while (1) {
        scanf("%d", &n);

        if (n == 0)
            break;

        int s = 0;
        int a[100];

        int k = 0; // 初始化为0

        for (int i = 0; i < n; i++) {
            scanf("%d", &a[i]);

            while (a[i] < k) {
                int c = k - a[i];
                s = s + c * 4;
                k = a[i];
            }

            while (a[i] > k) {
                int c = a[i] - k;
                s = s + c * 6;
                k = a[i];
            }

            // 添加停留时间
            s = s + 5;
        }

        // 输出每个测试用例的总时间,换行
        printf("%d\n", s);
    }

    return 0;
}

  • 8
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值