C语言:PAT练习:水仙花数( T & F)

水仙花数

  1. 算法思路
    1、当输入 n 位数时对所求数值划定范围并从小到大判断数值是否符合要求, 例如当 n = 3 时,范围为 100 -999 之间;
    2、分别取不同位的数值,进行 n 次幂运算;
    3、比较运算结果是否合理,进行输出。
  2. 错误代码:
// 水仙花数
#include<stdio.h>
int main()
{
	int a;
	int b=1;
	int c=1;
	int d;
	int e;
	int sum=0;
	int f=1;
	int g;
	int h;
	printf("please input number(3-8):");
	scanf("%d",&a);
		while(b<a){
			c*=10;
			b++;
		}
		d=c;
		while(c<c*10){			
			while(d>0){			
				e=d%10;
				g=a;
				d/=10;				
				while(g>=1){
					f*=e;
					g--;
				}
				sum+=f;			
				if(sum==c){
				printf("水仙花数为%d\n",c);
				}
				f=1;
								
			}
			sum=0;
			c++;
			d=c;
		}
		return 0;
 } 

代码输出:
		please input number(3-8):3
		水仙花数为125
		水仙花数为153
		水仙花数为216
		水仙花数为370
		水仙花数为371
		水仙花数为407
		水仙花数为729
		
		--------------------------------
		Process exited after 22.57 seconds with return value 0
		请按任意键继续. .

代码分析:sum+=f; if(sum==c){ printf("水仙花数为%d\n",c);
这里的 if 条件语句设置会出现三位数值中当其中两位的n次幂运算等于所求数值时,直接输出错误结果。

  1. 正确代码
#include <stdio.h>
int main()
{
	int a;
	scanf("%d",&a);
	int b=1;
	int c=1;
	while(b<a){
		c*=10;
		b++;		
	}
	while(c<c*10){
		int d;
		int e=c;
		int sum=0;
		while(e>0){
			d=e%10;
			e/=10;
			int f=0;
			int g=1;
			while(f<a){
				g*=d;
				f++;
			}
			sum+=g;
		}
			if(sum == c){
			printf("%d\n",sum);
		}
		
		c++;
	}
	
 } 

代码输出:
		3
		153
		370
		371
		407
		
		--------------------------------
		Process exited after 22.07 seconds with return value 0
		请按任意键继续. . .

代码分析:
当输入整数位数 n 时首先进行转换成该整数位数下的最下值,然后对最小值进行取余后运算得到每位的 n 次幂,然后累加结果并比较当前数值是否相同。

  1. 总结
    错误程序的原因在于if(sum==c){ printf("水仙花数为%d\n",c);}语句写在了取余运算循环的内部,这就导致了即使在取余运算未结束时,当小于 n 位余数满足 n 次幂的结果相加和等于运算数值,即使不是满足结果也会强行输出运算数值。
    当程序存在多重循环时,一定要理清楚循环单个循环实现的意义,还有就是循环类似于函数,在循环内部定义的变量,在循环外部便不会存在。
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值