最近在复习c语言的一些知识点,以下是整理的几道比较重要的编程题:
1.打印100-200之间的素数
为了统计素数的个数,可设置一个计数器count;
方法1:
#include<stdio.h>
int main()
{
int i = 0;
int count = 0;
for (i = 100; i <= 200; i++)
{
//判断i是否为素数
int j = 0;
for (j = 2; j <= i; j++)
{
if (i%j == 0)
break;
}
if (j == i)
{
printf("%d ", i);
count++;
}
}
printf("\ncount=%d\n", count);
system("pause");
return 0;
}
方法2:
#include<stdio.h>
int main()
{
int i = 0;
int count = 0;
for (i = 100; i <= 200; i++)
{
//判断i是否为素数
int j = 0;
for (j = 2; j <= i/2; j++)
{
if (i%j == 0)
break;
}
if (j > i/2)
{
printf("%d ", i);
count++;
}
}
printf("\ncount=%d\n", count);
system("pause");
return 0;
}
方法3:
这里用的是开方法,需要引入头文件math.h
#include<stdio.h>
#include<math.h>
int main()
{
int i = 0;
int count = 0;
for (i = 100; i <= 200; i++)
{
//判断i是否为素数
int j = 0;
for (j = 2; j <= sqrt(i); j++)
{
if (i%j == 0)
break;
}
if (j >sqrt(i))
{
printf("%d ", i);
count++;
}
}
printf("\ncount=%d\n", count);
system("pause");
return 0;
}
运行结果:
2.打印99乘法表
#include<stdio.h>
int main()
{
int i = 0;
for (i = 1; i <= 9; i++)
{
int j = 0;
for (j = 1; j <= i; j++)
{
printf("%d*%d=%-2d ", i,j,i*j);
}
printf("\n");
}
system("pause");
return 0;
}
运行结果:
3.打印1000-2000之间的闰年
闰年的计算方法是能被4整除并且能被100整除或者能被400整除
if(((year%40)&&(year%100!=0))||(year%4000))
代码如下:
#include<stdio.h>
int main()
{
int year = 0;
int count = 0;
for (year = 1000; year <= 2000; year++)
{
if (year % 4 == 0)
{
if (year % 100 != 0)
{
count++;
printf("%d ", year);
}
}
if (year % 400 == 0)
{
count++;
printf("%d ", year);
}
}
printf("\ncount=%d\n", count);
system("pause");
return 0;
}
运行结果:
以上,都是一些简单的编程,以后会继续更新。。。。。。