int Distance() {
char from[40], to[40];
double val;
double result;
printf("Enter what you want to convert from: ");
fflush(stdin);
fgets(from, 40, stdin);
printf("Enter what you want to convert to: \n");
fflush(stdin);
fgets(to, 40, stdin);
printf("Enter the numerical value of conversion: \n");
scanf("%lf", &val);
(strcmp(from, "cm") == 0 && strcmp(to, "mm") == 0) ? printf("Answer is %lf MilliMeters", val / 10) :
(strcmp(from, "mm") == 0 && strcmp(to, "cm") == 0) ? printf("Answer is %lf CentiMeters", val * 10) :
(strcmp(from, "cm") == 0 && strcmp(to, "km") == 0) ? printf("Answer if %lf KiloMeters", val * 100000) :
(strcmp(from, "km") == 0 && strcmp(to, "cm") == 0) ? printf("Answer is %lf CentiMeters", val / 100000) :
(strcmp(from, "mm") == 0 && strcmp(to, "km") == 0) ? printf("Anser is %lf KiloMeters", val * 1000000) :
(strcmp(from, "km") == 0 && strcmp(to, "mm") == 0) ? printf("Answer is %lf MilliMeters", val / 1000000) :
printf("Please enter valid conversion units");
}
我正在尝试制作一个单位转换器。所以我为不同的转换制作了不同的函数 - 例如int distance()
,
int time()
等等。
在计算距离的函数中,我使用 fgets()
来获取多字符输入,例如“cm”、“mm”等。
我想要实现的是
如果 char from
中的 fgets
值为“任何字符串”,并且 char to
中的 fgets
值为“任何其他字符串” ": 打印结果,其公式为-----(something)
不计算结果,直接跳转到最终的printf("请输入有效的换算单位")
我仍处于初级学习阶段,这可能是一个小错误,请帮忙。
最佳答案
代码中存在多个问题:
fgets()
将尾随换行符存储在目标数组的末尾,因此与单位字符串的所有比较都将失败。- 您应该使用中间单元以避免测试所有组合。
这是修改后的版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct unit {
double factor;
const char *abbrev, *singular, *plural;
} const units[] = {
{ 1, "mm", "millimeter", "millimeters" },
{ 10, "cm", "centimeter", "centimeters" },
{ 100, "dm", "decimeter", "decimeters" },
{ 1000, "m", "meter", "meters" },
{ 10000, "dam", "decameter", "decameters" },
{ 100000, "hm", "hectometer", "hectometers" },
{ 1000000, "km", "kilometer", "kilometers" },
{ 25.4, "in", "inches", "inches" },
{ 304.8, "ft", "foot", "feet" },
{ 914.4, "yd", "yards", "yards" },
{ 201168, "fur", "furlong", "furlongs" },
{ 1609344, "mi", "mile", "miles" },
};
int get_unit(void) {
char buf[40];
while (fgets(buf, sizeof buf, stdin)) {
buf[strcspn(buf, "\n")] = '\0'; // remove the newline if any
for (int i = 0, n = sizeof(units) / sizeof(*units); i < n; i++) {
if (!strcmp(buf, units[i].abbrev)
|| !strcmp(buf, units[i].singular)
|| !strcmp(buf, units[i].plural)) {
return i;
}
}
printf("unknown unit\n");
}
printf("unexpected end of file, aborting\n");
exit(1);
}
int main(void) {
int from, to;
double val;
printf("Enter what you want to convert from: ");
from = get_unit();
printf("Enter what you want to convert to: ");
to = get_unit();
printf("Enter the numerical value of conversion: ");
if (scanf("%lf", &val) == 1) {
double result = val * units[from].factor / units[to].factor;
printf("Answer is %g %s\n", result, result == 1 ? units[to].singular : units[to].plural);
return 0;
}
return 1;
}
关于c - C 有没有办法比较多个字符串? [我通过fgets()输入它们],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76627995/