You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言中如何解析分数字符串?实现create_fraction_from_string函数

实现create_fraction_from_string函数的最简方法

因为你的输入格式固定为"x/y"或"-x/y",直接用标准库的sscanf函数是最简洁的实现方式,无需手动拆分字符串,它会自动处理负号并提取整数。

完整代码示例

#include <stdio.h>

// 定义分数结构体
typedef struct {
    int a; // 分子
    int b; // 分母
} fraction;

fraction create_fraction_from_string(const char* str) {
    fraction frac;
    // 按格式直接提取分子和分母
    sscanf(str, "%d/%d", &frac.a, &frac.b);
    return frac;
}

// 测试用例
int main() {
    fraction f1 = create_fraction_from_string("15/5");
    printf("分子:%d,分母:%d\n", f1.a, f1.b); // 输出:分子:15,分母:5
    
    fraction f2 = create_fraction_from_string("-12/4");
    printf("分子:%d,分母:%d\n", f2.a, f2.b); // 输出:分子:-12,分母:4
    
    return 0;
}

代码说明

  • sscanf(str, "%d/%d", &frac.a, &frac.b):格式字符串"%d/%d"会精准匹配输入的整数-斜杠-整数结构,%d会自动识别正负号,直接将对应数值存入结构体的分子和分母成员。
  • 若后续需要处理非法输入(比如格式不符合要求),可以判断sscanf的返回值:返回2表示成功提取两个整数,返回其他值则说明输入无效。

内容的提问来源于stack exchange,提问作者lukkkss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:50:44