我正在用 C 语言创建一个温度转换器。基本上,您输入以摄氏度为单位的最小值和最大值,以及一个步骤,它会在列表中显示该信息以及等效的华氏度。在某些情况下,我注意到最后一个华氏度条目没有在应该显示的时候显示。例如,当您输入下限 10、上限 30、步长 4 时,它会截断最后的华氏温度。我知道这与最后一个 while 循环有关,但我就是想不通。
#include <stdio.h>
int main (int argc, const char * argv[]) {
double l, h, s;
double lf, hf, sf;
/* Number rows in tables */
int num1, num2;
num1 = 1;
num2 = 1;
/* Lower limit input */
printf("Please give a lower limit: ");
scanf("%4lf", &l);
while (l < 0) {
printf("Lower limit must be greater than 0: ");
scanf("%4lf", &l);
}
/* Stores value for Fahrenheit conversion */
lf = l;
/* Higher limit input */
printf("Please give a higher limit: ");
scanf("%4lf", &h);
while (h <= l) {
printf("Higher limit must be greater than lower limit: ");
scanf("%4lf", &h);
}
while (h >= 50000) {
printf("Higher limit must be less than 50000: ");
scanf("%4lf", &h);
}
hf = h;
/* Step input */
printf("Please input step: ");
scanf("%4lf", &s);
while (s <= 0) {
printf("Step must be greater than 0: ");
scanf("%4lf", &s);
}
while (s >= h - l) {
printf("Step must be less than the difference in temperatures: ");
scanf("%4lf", &s);
}
sf = s;
/* Celsius table */
printf("\nCelsius\n-------\n");
while (l <= h) {
printf("%i. %4lf\n", num1, l);
num1++;
l = l + s;
}
/* Fahrenheit table */
printf("\nFahrenheit\n----------\n");
/* Converts Celsius to Fahrenheit */
lf = (lf * 1.8) + 32;
hf = (hf * 1.8) + 32;
sf = sf * 1.8;
printf("Lower input: %4lf\n", lf);
printf("Higher input: %4lf\n", hf);
printf("Step: %4lf\n----------\n", sf);
/* This while loop sometimes cuts off the last entry */
while (lf <= hf) {
printf("%i. %4lf\n", num2, lf);
num2++;
lf = lf + sf;
}
return 0;
}
问题在于比较 double ,您可能会遇到类似 10 + 1.8
的计算结果为 11.800000001
的情况,因此会丢失最终值。
您的问题的解决方案是首先计算步数:
int steps = (h - l) / s + 1; //Might want to apply rounding
然后使用 for/while
循环遍历整数变量:
for (int i = 0; i < steps; ++i) {
double t = l + (h - l) * i / (steps - 1);
}
for (int i = 0; i < steps; ++i) {
double tf = lf + (hf - lf) * i / (steps - 1);
}
我是一名优秀的程序员,十分优秀!