1、求10 个整数中最大值。
利用容量为10的数组去存储这10个数,假设arr[0]所代表的数为最大,依次用arr中的数与max进行比较,如果arr[i]>max,则将arr[i]赋值给max,最终在比较完数组中的数之后,输出最大的那一个。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int arr[10];
int i,max;
printf("输入10个整数:");
for (i = 0;i < 10;i++)
{
scanf("%d", &arr[i]);
max = arr[0];
}
for (i = 0;i < 10;i++)
{
if (arr[i] > max)
{
max = arr[i];
}
}
printf("最大值为:%d\n", max);
system("pause");
return 0;
}
2、将三个数按从大到小输出。(建立临时变量)
利用中间变量进行数值的交换,比较a、b,把较大值存储在a中,在比较a、c,同样最大值赋给a,这样保证了a始终存储的数是三个数中最大的。最后对b、c进行比较,大值赋给b,小值为c,,用printf依次输出a、b、c,即从大到小顺序。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a, b, c, t;
scanf("%d %d %d", &a, &b, &c);
if (a < b)
{
t = a;
a = b;
b = t;
}//首先判断a与b的大小,将较大的放在a中;
if (a<c)
{
t = a;
a = c;
c = t;
}//其次判断a与c的大小,将较大的放在a中;
if (b < c)
{
t = b;
b = c;
c = t;
}//最后判断b与c的大小,较大的存储在b中;
printf("%d %d %d\n", a, b, c);
system("pause");
return 0;
}
3、将数组A中的内容和数组B中的内容进行交换。(数组一样大)
同样采取创建中间变量的方式进行数组的交换。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, A[10], B[10], T[10];
printf("输入数组A:\n");
for (i = 0;i < 10;i++)
{
scanf("%d", &A[i]);
}
printf("输入数组B:\n");
for (i = 0;i < 10;i++)
{
scanf("%d", &B[i]);
}
for (i = 0;i < 10;i++)
{
T[i] = A[i];
A[i] = B[i];
B[i] = T[i];
}
printf("\n");
for (i = 0;i < 10;i++)
{
printf(" %d", A[i]);
}
printf("\n");
for (i = 0;i < 10;i++)
{
printf(" %d", B[i]);
}
printf("\n");
system("pause");
return 0;
}
4、计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值。
利用到C语言中pow()函数,引用头文件:#include<math.c>.其中pow()的作用是用来求x的y次幂,x,y函数值都是double型,即double pow(double x, double y); 则在本例中即为num=(-1)^(i+1)。
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
int i;
float sum = 0.0;
float num = 0.0;
float pow = 0.0;
for (i = 1; i <= 100; i++)
{
num = pow(-1, i + 1);
sum = sum + num * 1 / i;
}
printf("sum is %f\n", sum);
system("pause");
return 0;
}
5、编写程序数一下 1到 100 的所有整数中出现多少次数字9。
对1~100之间的数进行for循环,当int n = num % 10; 且满足n == 9时,count++,进行统计出现9的次数。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i = 1;
int num = 0;
int count = 0;
for (i=1;i <= 100;i++)
{
num = i;
while (num>0)
{
int n = num % 10;
if (n == 9)
{
count++;
}
num /= 10;
}
}
printf("%d\n", count);
system("pause");
return 0;
}