基础方法判断Armstrong数/回文数:C语言代码输出异常求助
问题分析与修复方案
你的代码核心问题是变量赋值逻辑完全错误,导致后续计算回文数和Armstrong数的逻辑根本没基于输入的数值执行,所以无论输入什么,输出结果都一致。
具体错误点
- 赋值顺序颠倒:输入
org后,你写了org=a1;和org=a;,这是把未初始化的a1、a的垃圾值覆盖掉了用户输入的数值。正确操作应该是把输入的org赋值给a和a1,作为计算时的副本。 - 未初始化变量风险:
a和a1在赋值前没有初始化,会携带随机垃圾值,导致两个while循环的执行逻辑完全偏离预期,最终c(回文数计算结果)和e(Armstrong数立方和)无法正确对应输入的数值。
修复后的代码
#include <stdio.h> int main(){ int a,b,c=0,d,e=0,a1,org; printf("Please enter your three digit number: "); scanf("%d",&org); // 将输入的原始数值赋值给a和a1,作为计算副本 a = org; a1 = org; // 计算回文数 while(a!=0){ b=a%10; c=c*10+b; a=a/10; } // 计算Armstrong数(各位立方和) while(a1!=0){ d=a1%10; e=e+d*d*d; a1=a1/10; } if(c==org && e==org){ printf("The entered number is both a palindrome and an armstrong"); } else if(e==org && c!=org){ printf("The entered number is an armstrong"); } else if(c==org && e!=org){ printf("The entered number is a palindrome"); } else{ printf("The entered number is not a palindrome or an armstrong"); } return 0; }
额外优化建议
- 增加输入校验,确保用户输入的是三位数:
if(org < 100 || org > 999){ printf("Please enter a valid three-digit number!\n"); return 1; } - 优化变量命名,比如将
c改为palindrome_num、e改为armstrong_sum,提升代码可读性。
内容的提问来源于stack exchange,提问作者Timupuu
相关产品推荐
相关产品推荐

