C语言 循环练习 练练手

C语言 循环练习

计算所有的3位水仙花数

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

bool isnarcissistic(const int n);

int main(int argc,const char* argv[])
{
	for(int i = 100; i < 1000; i++)
	{
		if(isnarcissistic(i))
		{
			printf("%d\n",i);
		}
	}
}

bool isnarcissistic(const int n)
{
	int ones = n % 10;
	int tens = n / 10 % 10;
	int hundreds = n / 100;
	return pow(ones,3) + pow(tens,3) + pow(hundreds,3) == n;
}

输入一个正整数,判断是否是素数

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

bool isprime(const int n);

int main(int argc,const char* argv[])
{
	int num;
	printf("请输入正整数:");
	scanf("%d",&num);
	if(num <= 0)
	{
		printf("输入不合法,请重新输入!\n");
		scanf("%d",&num);
	}
	else if(isprime(num))
	{
		printf("%d是素数\n",num);
	}
	else
	{
		printf("%d不是素数\n",num);
	}
}

bool isprime(const int n)
{
	if(n == 1)
	{
		return 1;
	}
	else
	{
		for(int i = 2; i <= sqrt(n); i++)
		{
			if(0 == n % i)
			{
				return 0;
			}
		}
	}
	return 1;
}

输入一个正整数,判断是否是一个回文数

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

bool palindrome(const int n);

int main(int argc,const char* argv[])
{
	int num;
	printf("请输入一个正整数:");
	scanf("%d",&num);

	if(palindrome(num))
	{
		printf("%d是回文数",num);	
	}
	else
	{
		printf("%d不是回文数",num);	
	}
}

bool palindrome(const int n)
{
	int cnt = 0,tmp = n;
	while(tmp)
	{
		cnt = cnt* 10 + tmp % 10;
		tmp /= 10;
	}
	if(n == cnt)
	{
		return 1;	
	}
	return 0;
}

不使用循环 计算n的阶乘

#include <stdio.h>
#include <stdlib.h>

int main()
{
	int num = 0,temp = 1,cnt = 0;
	printf("请输入一个数:");
	scanf("%d",&num);
	cnt = num;
	loop:
	temp *= cnt--;
	if(cnt)
	{
		goto loop;
	}
	printf("!%d = %d\n",num,temp);
}

打印 9 * 9 乘法表

#include <stdio.h>
#include <stdlib.h>

int main()
{
	for(int i = 1;i < 10;i++)
	{
		for(int j = 1;j < 10;j++)
		{
			if(i >= j)
			{
				printf("%d*%d=%02d  ",i,j,i*j);
			}
		}
		printf("\n");
	}
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值