用C语言打印水仙花数(for ,while,goto三种方法)

问题描述

输出所有的“水仙花数”,所谓的“水仙花数”是指一个三位数其各位数字的立方和等于该数本身,例如153是“水仙花数”,因为:153 = 13 + 53 + 33。

问题分析

根据“水仙花数”的定义,判断一个数是否为“水仙花数”,最重要的是要把给出的三位数的个位、十位、百位分别拆分,并求其立方和(设为s),若s与给出的三位数相等, 三位数为“水仙花数”,反之,则不是。

算法设计

“水仙花数”是指满足某一条件的三位数,根据这一信息可以确定整数的取值范围是 100〜999。

对代码的说明:

  • 将n整除以100,得出n在百位上的数字hun。
  • 将(n-i*100)整除以10(或将n先整除以10再对10求模n/10%10),得出n在十位上的数字ten。
  • 将n对10取余,得出n在个位上的数字ind。
  • 求得这三个数字的立方和是否与其本身相等,若相等,则该数为水仙花数。

用for语句

#include <stdio.h>
#include <math.h>
int main(int argc, const char *argv[])
{
	int hun,ten,ind;
    int n = 100;
	printf("result is:");
	
	for(;n <= 999;n++){
		hun = n / 100;
		ten = n /10 % 10;
		ind = n % 10;
		
//		if (n == hun*hun* hun + ten*ten*ten + ind*ind*ind )
		if (pow(hun, 3) + pow(ten, 3) + pow(ind ,3) == n)
		printf("%d ",n);
	}
    printf("\n");
    return 0;
}

用while语句

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

int main(int argc, const char *argv[])
{
	int hun, ten, ind;
	int n = 100;

	printf("result is:");
	
	while(n <= 999){
		hun = n / 100;    
		ten = n /10 % 10;
		ind = n % 10;
		
	//	if (hun*hun* hun + ten*ten*ten + ind*ind*ind == n )
		if (pow(hun, 3) + pow(ten, 3) + pow(ind, 3) == n)
			printf("%d ",n);
		n++;
	}
    printf("\n");
    return 0;
}

用goto 语句

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

int main(int argc, const char *argv[])
{
	int hun, ten, ind;
	int n = 100;

	printf("result is:");

_loop:
	if(n <= 999){
		hun = n / 100;
		ten = n /10 % 10;
		ind = n % 10;
		
	//	if (hun*hun* hun + ten*ten*ten + ind*ind*ind == n )
		if (pow(hun, 3) + pow(ten, 3) + pow(ind, 3) == n)
		printf("%d ",n);
		n++;
    	goto _loop;
	}
    printf("\n");
    return 0;
}

运行结果

result is:153  370  371  407

 

参考:http://c.biancheng.net/view/504.html

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

攻城狮晨哲

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值