提问人:archlotteatir 提问时间:9/22/2023 最后编辑:archlotteatir 更新时间:9/22/2023 访问量:80
C题已解决,但无法通过测试系统(超时)
C question solved but cannot pass the test system(timeout)
问:
我是 C 语言的初学者,我一直在做作业,但我在解决问题时遇到了麻烦
问题来了:
给定房屋大小的下限 N(以坪为单位),并且 尺寸 {hi} 的集合(以 m2 为单位),搜索满足 条件大小小于 N。您应该将单位转换为 平壤。假设一个坪是 3.3058m2。例如,如果您想要一个 房屋不超过 5 坪 (N = 5),并且大小不一 {5.7,10.1,20.4,15.2,17.6},小于或等于 5 的大小集 平是{5.7,10.1,15.2}。最大的是 15.2m2,这是 约4.60坪。因此,您的程序应打印 4.60。这 输入由标准输入中的两行组成。第一行包含 上限 N 和第二行包含房屋的大小 hi, 由空格隔开。房屋的大小数量大于 零。
您的程序应该找到满足条件的合适大小 h, 并计算平移后的 N′。输出由两个组成 行:第一行包含 N′,第二行包含 h。所有印刷品 值应在小数点后四舍五入到小数点后三位 点。如果没有房屋满足条件,则应打印程序 两行均为零。
所以输入应该是这样的:(例如)
5
5\.7 10.1 20.4 15.2 17.6
输出应如下所示:
4\.60
15\.20
另一个例子:
20
59\.528 34.141 73.272 62.509
18\.91
62\.51
以下是我的代码:
#include <stdio.h>
int main(){
int lower_bound;
int count = 0; //the index where the element is to be inserted
float arr[10];//initialize an array
float pyeong = 3.3058;
//get lower bound
scanf("%d", &lower_bound);
//get the size(float numbers)
do {
scanf("%f", &arr[count++]);
}while (getchar() != '\n');
//resize the array
//arr[count];
//print array element
for (int i = 0; i < count; i++){
if(arr[i] < lower_bound*pyeong){
if(arr[i]> arr[0]){ //compare which one is bigger
arr[0] = arr[i];//put the bigger one in the front
}
}else{
arr[i] = 0;
}
}
//printf("%.2f\n", lower_bound*pyeong);
printf("%.2f\n", arr[0]/pyeong);
printf("%.2f\n", arr[0]);
return 0;
}
我已经在 VS Code 和 Codeblock 中测试了我的代码,当我上传到代码测试平台(由学校设计)时,它显示“超时”消息。
我可以知道程序中的循环是否导致错误吗?请在代码中提供有价值的反馈和改进。
答:
这在竞争性编程中很常见。如果您在谷歌上搜索“TIME LIMIT EXCEEDED”,它会提供可能的原因和解决方案。
我在您的代码中指出的一点是固定的,应该是常量。那么,为什么要每次都进行乘法运算呢?lower_bound
const float pyeong = 3.3058;
它应该是这样的:
float area = lower_bound*pyeong;
for (int i = 0; i < count; i++){
if(arr[i] < area){
if(arr[i]> arr[0]){ //compare which one is bigger
arr[0] = arr[i];//put the bigger one in the front
}
}else{
arr[i] = 0;
}
}
评论
%.3f
float output = 0;
arr[0]
else
if((arr[i] < area) && (output < arr[i])) output = arr[i];
评论
"%.2f\n"
while (getchar() != '\n');
并非所有文本文件都以 ...一些编辑器可以保存带有“悬空”最后一个单词(或其他任何单词)的文件。也许可以调查一下......\n
echo "foo\nbar" | studentsProg
...一种可能的“测试工具”,省略了预期的尾随换行符......你的程序将坐下来等待,直到宇宙的热寂。scanf()
返回它所做的分配数。使用该值!! 假设输入格式良好(通常用于此类练习,与与真人打交道时不同)while (scanf("%f", &arr[count]) == 1) { count++; } /* no getchar!! */