移植预订模块
Coddy 面向 Lua 开发者的 C 课程的第 48 课,共 48 课。
挑战
中等使用包含 remaining 字段的 Room 结构体和 room_reserve(Room*,request),移植 Lua 预约算法。容量是非负整数,请求是整数。只接受大于 0 且不超过剩余容量的请求,并返回 true,同时减少 remaining。拒绝请求时不修改数据。输入为容量,后跟多个请求;打印 remaining:accepted。锁定的 main 会独立测试两个房间和失败的更新。这是结构体和函数接口,不是 C 类。
Lua 参考
local values={}
for word in io.read("a"):gmatch("%S+") do
values[#values+1]=tonumber(word)
end
local capacity=values[1]
local remaining=capacity
local accepted=0
for i=2,#values do
local request=values[i]
if request>0 and request<=remaining then
remaining=remaining-request
accepted=accepted+1
end
end
print(remaining..":"..accepted)编辑未锁定的源文件和头文件。确保声明的公共 API 与可见的锁定文件 main.c 兼容,因为它会直接调用该 API。不要添加另一个 main。除非任务明确检查数值范围,否则所有数字测试数据都足够小,不会导致溢出。只打印指定的输出;如果提供了驱动程序,它会负责解析输入和生成输出。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){Room a={3},b={5};if(room_reserve(&a,0)||room_reserve(&a,-1)||room_reserve(&a,4)||a.remaining!=3||!room_reserve(&a,2)||a.remaining!=1||b.remaining!=5)return 3;Room room;if(scanf("%d",&room.remaining)!=1)return 1;int request,accepted=0;while(scanf("%d",&request)==1)if(room_reserve(&room,request))accepted++;printf("%d:%d\n",room.remaining,accepted);return 0;}
面向 Lua 开发者的 C中的所有课
自己练习: C 在线编译器