1. 写一个函数可以判断一个数是不是素数。
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<math.h>
int is_sushu (int x1)
{
int j = 0;
for (j = 2; j <= sqrt(x1); j++)
{
if (x1%j == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int num = 0;
scanf("%d", &num);
int i = 0;
if ((i=is_sushu(num)) == 1)
{
printf("%d是素数", num);
}
else
{
printf("%d不是素数", num);
}
system("pause");
return 0;
}
2. 写一个函数判断一年是不是闰年。
int is_rn(int year)
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
{
return 1;
}
return 0;
}
int main()
{
int i = 0;
scanf("%d", &i);
if ((is_rn(i)) == 1)
{
printf("%d是闰年\n", i);
}
else
{
printf("%d不是闰年\n", i);
}
system("pause");
return 0;
}
3. 写一个函数,实现一个整形有序数组的二分查找。int binary_search(int arr[], int key, int left, int right)
{
while (left<=right)
{
int mid = left - (left - right)/2;
if (arr[mid] < key)
{
left = mid + 1;
}
else if (arr[mid]>key)
{
right = mid - 1;
}
else
{
return mid;
}
}
if (left > right)
{
return -1;
}
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
int ret = binary_search(arr, 5, 3, 5);
if (ret != -1)
{
printf("%d", ret);
}
else
{
printf("没找到\n");
}
system("pause");
return 0;
}
4. 写一个函数,只要调用一次就可以将参数的值,增加1。void zyd(int* p)
{
(*p)++;
}
int main()
{
int num = 0;
scanf("%d", &num);
zyd(&num);
printf("%d", num);
system("pause");
return 0;
}
5. 在屏幕上输出以下图案:*
***
*****
*******
*********
***********
*************
***********
*********
*******
*****
***
*
int main()
{
int i, j, a, n, x, d;
scanf("%d", &d); //(这里输入菱形的总行数)
x = (d + 1) / 2;
for (i = -x; i <= x; i++)
{
if (i <= 0)
{
n = (i + x);
}
else
{
n = (-i + x);
}
for (a = 1; a <= 10 - n; a++)
{
printf(" ");
}
for (j = 1; j <= n * 2 - 1; j++)
{
printf("*");
}
printf("\n");
}
system("pause");
return 0;
}
6.求出0~999之间的所有“水仙花数”并输出。“水仙花数”是指一个三位数,其各位数字的立方和确好等于该数本身,如;153=1+5+3?,则153是一个“水仙花数”。
/*
在数论中,水仙花数(Narcissistic number)也称为自恋数、自幂数、阿姆斯壮数或阿姆斯特朗数(Armstrong number),是指一N位数,其各个数之N次方和等于该数。
例如153、370、371及407就是三位数的水仙花数,其各个数之立方和等于该数:
153 = 1^3 + 5^3 + 3^3。
370 = 3^3 + 7^3 + 0^3。
371 = 3^3 + 7^3 + 1^3。
407 = 4^3 + 0^3 + 7^3。
*/
#include<math.h>
int main()
{
int i = 0;
for (i = 0; i < 1000; i++)
{
int temp = i; int count = 0; int sum = 0;
while (temp)
{
count++;
temp = temp / 10;
}
temp = i;
while (temp)
{
sum += pow((temp % 10), count);
temp /= 10;
}
if (sum == i)
{
printf("%d ", i);
}
}
system("pause");
return 0;
}
7.求Sn=a+aa+aaa+aaaa+aaaaa的前5项之和,其中a是一个数字,例如:2+22+222+2222+22222
int main()
{
int a = 2;
int n = 5;
int sum = 0;
int i = 0;
int ret = 0;
for (i = 0; i < n; i++)
{
ret = ret * 10 + a;
sum += ret;
}
printf("sum=%d", sum);
system("pause");
return 0;
}
8.编写一个程序,它从标准输入读取C源代码,并验证所有的花括号都正确的成对出现。{}
{}{}
{{}}
{{{}}}}
int main()
{
int ch = 0;
int count = 0;
while ((ch = getchar()) != EOF)
{
if (ch == '{')
{
count++;
}
else if (ch == '}')
{
if (count > 0)
{
count--;
}
else if (count==0)
{
printf("不匹配\n");
return 0;
}
}
}
if (count == 0)
{
printf("匹配\n");
}
else
{
printf("不匹配\n");
}
system("pause");
return 0;
}