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

C语言中如何在数字间插入文本?例:将1514转为15:14

在C语言中给数字变量插入文本(如1514→15:14)的实现方法

嘿,这个需求其实挺常见的,给你两种简单实用的实现方式:

  • 直接格式化输出:利用整数除法和取模运算拆分数字,再通过printf的格式控制符插入冒号。代码示例:

    #include <stdio.h>
    
    int main() {
        int a = 1514;
        // 拆分出前两位和后两位,%02d确保后两位不足两位时补前导零
        printf("%d:%02d\n", a / 100, a % 100);
        return 0;
    }
    

    运行后会输出15:14。如果你的数字可能是三位数(比如123),想要输出01:23这种补零格式,只需要把格式符改成%02d:%02d即可。

  • 将结果存入字符串:如果需要把格式化后的结果保存到字符串中供后续使用,可以用sprintf函数:

    #include <stdio.h>
    
    int main() {
        int a = 1514;
        char formatted_str[10]; // 预留足够空间存储结果
        sprintf(formatted_str, "%d:%02d", a / 100, a % 100);
        printf("%s\n", formatted_str); // 输出15:14
        return 0;
    }
    

这两种方法都能轻松实现你要的效果,根据实际需求选就行~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:42:06