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 fromfgets的值是"任意字符串",char to中的fgets是"任何其他字符串":打印结果,其公式是-(Something)

它不计算结果,直接跳到最后printf("Please enter valid conversion units")

我还在初学阶段,可能是个小错误,请帮帮忙.

推荐答案

代码中存在多个问题:

  • 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函数调用asm函数时生成错误的BLX指令(STM32H753上的gcc)

无效使用未定义类型'structsquare'?

为什么sscanf不能正确地从这个字符串格式中提取所有数字?

具有交换链获取和命令缓冲区提交的同步-危险-读后写错误

如何捕捉只有换行符或空格字符缓冲区的边缘大小写

整型文字后缀在左移中的用途

错误Cygwin_Except::Open_stackdupfile:正在转储堆栈跟踪是什么?

在创建动态泛型数组时,通过realloc对故障进行分段

getline()从c中的外部函数传递指针时输出null

为什么双精度d=flt_max+flt_max;在c语言中得到inf的结果

如何在提取的索引中分配空值?

处理EPOLL_WAIT中的接收数据和连接关闭信号

在vfork()之后,链接器如何在不 destruct 父内存的情况下解析execve()?

当我用scanf(&Q;%S%S%S&Q;,单词0,单词1,单词2)输入多个单词时,除了最后一个单词外,每个单词的第一个字符都丢失了

如何编写postgresql支持函数

I';我试着从.txt文件中读取文本,并用c计算其中的单词数量

在NASM中链接Linux共享库时出错-';将R_ X86_64_;foo';

If语句默认为true

与指针的原始C数组或C++向量<;向量<;双>>;

为什么<到达*时不会转换为>?