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

C语言:仅用循环拆分整数各位数字至每行的代码修复求助

修复你的数字提取代码问题

我看到你的代码里第二个循环确实有几个关键问题,咱们一步步来解决:

主要问题分析

  • 原始x被修改:第一个循环里你直接把输入的x反复除以10,计算完位数后x已经变成0了,第二个循环再用x自然拿不到任何有效数字。
  • pow函数的精度陷阱:pow是浮点函数,返回的结果可能有精度误差(比如pow(10,2)可能实际是99.999999999),转成int后就会变成99,导致后续的数字提取错误。
  • 循环终止条件错误:第二个循环的while(factor>0)会导致死循环,因为factor是10的幂次,永远不会变成0。

修复后的代码

#include <stdio.h>

int main() {
    int x, dg, num, factor;
    int orig_x; // 保存原始输入的x

    printf("Enter x:");
    scanf("%d", &x);
    orig_x = x; // 把输入值存起来,避免被第一个循环修改

    // 计算位数
    num = 0;
    int temp = orig_x;
    while (temp > 0) {
        temp /= 10;
        num++;
    }
    printf("%d is the number of digits\n", num);

    // 提取每一位数字
    factor = 1;
    // 先计算最高位的除数(比如3位数就是100)
    for (int i = 1; i < num; i++) {
        factor *= 10;
    }

    while (factor > 0) {
        dg = orig_x / factor;
        printf("%d ", dg); // 输出每一位数字
        orig_x = orig_x % factor;
        factor /= 10; // 除数降一位
    }

    return 0;
}

关键修改说明

  1. 保存原始输入:新增orig_x变量存储用户输入的初始值,第一个循环用temp来计算位数,避免修改原始数据。
  2. 用整数运算替代pow:通过循环乘以10来计算最高位的除数,完全避免浮点精度问题。
  3. 修正循环终止条件:每次循环后把factor除以10,当factor变成0时自然退出循环,同时逐个提取并输出每一位数字。

测试一下,比如输入1234,程序会输出4 is the number of digits,然后输出1 2 3 4,完美解决你的问题~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:45:57