我正在为一个网站做一个编码挑战,前提是:
在这个挑战中,编写一个接受三个参数的程序,一个起始温度(摄氏度)、一个结束温度(摄氏度)和一个步长。以步长为单位打印从 > 开始温度到结束温度的表格;如果步长不完全匹配,您实际上不需要打印最终结束温度。您应该执行输入验证:不接受低于下限(您的代码应指定为常数)或高于上限(您的代码也应指定)的起始温度。您不应允许步长大于温差。(本练习基于 C 编程语言中的一个问题)。
我得到了与解决方案相同的结果,但我很好奇为什么他们的解决方案更有效(我想是这样)。有谁能给我解释一下吗?他们的解决方案首先是我的。
#include <stdio.h>
#define LOWER_LIMIT 0
#define HIGHER_LIMIT 50000
int main(void) {
double fahr, cel;
int limit_low = -1;
int limit_high = -1;
int step = -1;
int max_step_size = 0;
/* Read in lower, higher limit and step */
while(limit_low < (int) LOWER_LIMIT) {
printf("Please give in a lower limit, limit >= %d: ", (int) LOWER_LIMIT);
scanf("%d", &limit_low);
}
while((limit_high <= limit_low) || (limit_high > (int) HIGHER_LIMIT)) {
printf("Please give in a higher limit, %d < limit <= %d: ", limit_low, (int) HIGHER_LIMIT);
scanf("%d", &limit_high);
}
max_step_size = limit_high - limit_low;
while((step <= 0) || (step > max_step_size)) {
printf("Please give in a step, 0 < step >= %d: ", max_step_size);
scanf("%d", &step);
}
/* Initialise Celsius-Variable */
cel = limit_low;
/* Print the Table */
printf("\nCelsius\t\tFahrenheit");
printf("\n-------\t\t----------\n");
while(cel <= limit_high) {
fahr = (9.0 * cel) / 5.0 + 32.0;
printf("%f\t%f\n", cel, fahr);
cel += step;
}
printf("\n");
return 0;
}
我的解决方案:
#include <stdio.h>
#include <stdlib.h>
#define LOW 0
#define HIGH 50000
int main(void)
{
int lower, higher, step, max_step;
float cel, fahren;
printf("\nPlease enter a lower limit, limit >= 0: ");
scanf("%d", &lower);
if (lower < LOW)
{
printf("\nERROR: Lower limit must be >= 0.");
exit(1);
}
printf("\nPlease enter a upper limit, limit <= 50000: ");
scanf("%d", &higher);
if (higher > HIGH)
{
printf("\nERROR: Upper limit must be <= 50,000.");
exit(1);
}
printf("\nPlease enter an increment amount, 0 < step <= 10: ");
scanf("%d", &step);
max_step = higher - lower;
if (step > max_step)
{
printf("\nERROR: Step size cannot exceed difference between higher and lower limit.");
exit(1);
}
printf("Celsuis \tFahrenheit\n");
printf("------- \t-----------\n\n");
cel = (float)lower;
while (cel < higher)
{
fahren = cel * 9/5 + 32;
printf("%f \t%f\n", cel, fahren);
cel = cel + step;
}
return 0;
}