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

C语言Armstrong数检测程序中input_num变量取值异常问题求助

C语言Armstrong数检测程序错误排查与修正

核心错误分析

你代码里拼接数字的逻辑完全错误:

int input_num;
for (j = 0; j < x; j++) {
  input_num = printf("%d", num[j]);
}

printf函数的返回值是成功打印的字符数量,不是你要拼接的数字。比如循环打印1、2、3时,每次printf都返回1(因为每个数字是1个字符),所以最后input_num的值是1。你看到的1231是先打印了123,然后又打印了input_num的1,并不是input_num本身是1231。

正确的数字拼接方法

初始化input_num为0,循环中通过数学运算拼接数字:

int input_num = 0;
for (j = 0; j < x; j++) {
  input_num = input_num * 10 + num[j];
}

比如数组元素是{1,2,3}:

  • 第一次循环:input_num = 0*10 +1 = 1
  • 第二次循环:input_num =1*10 +2=12
  • 第三次循环:input_num=12*10+3=123
    这样就能得到正确的拼接数字。

额外问题:pow函数的精度陷阱

pow(num[j], x)是浮点运算,直接转int可能出现精度误差。比如pow(3,3)可能返回26.999999,强制转int后变成26,导致结果错误。建议用整数循环计算幂,或者用round函数修正:

方法1:整数循环计算幂

int calculate_power(int base, int exp) {
    int result = 1;
    for(int i=0; i<exp; i++){
        result *= base;
    }
    return result;
}

然后在循环里调用:power[j] = calculate_power(num[j], x);

方法2:用round修正pow的结果

power[j] = (int)round(pow(num[j], x));

修正后的完整代码

#include <stdio.h>
#include <math.h>

int calculate_power(int base, int exp) {
    int result = 1;
    for(int i=0; i<exp; i++){
        result *= base;
    }
    return result;
}

int main(){
    int x, j, num[50];
    printf("Enter the size of your number: ");
    scanf("%d", &x);
    
    for (j = 0; j < x; j++) {
        printf("Write the %d th digit of your num: ", j + 1);
        scanf("%d", &(num[j]));
    }
    
    // 正确拼接数字
    int input_num = 0;
    for (j = 0; j < x; j++) {
        input_num = input_num * 10 + num[j];
    }
    printf("Input number: %d \n", input_num);
    
    int power[50];
    for (j = 0; j < x; j++) {
        // 使用整数幂计算避免精度问题
        power[j] = calculate_power(num[j], x);
        printf("%d\n", power[j]);
    }
    
    int sum = 0;
    for (j = 0; j < x; j++) {
        sum += power[j];
    }
    
    if (input_num == sum) {
        printf("Its an armstrong number!!!\n");
    } else {
        printf("not an armstrong no. :( \n");
    }
    return 0;
 }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 19:52:36