1.将数组A中的内容和数组B中的内容进行交换。(数组一样大)
法1:不建立函数
#include<stdio.h>
#include<stdlib.h>
int main1(){
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[10] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int i, tmp;
for (i = 0; i < 10; ++i){
printf("%d", a[i]);
}
putchar(’\n’);
tmp = a[i];
a[i] = b[i];
b[i] = tmp;
for (i = 0; i < 10; ++i){
printf("%d", b[i]);
}
putchar(’\n’);
system(“pause”);
return 0;
}
法2:建立函数
#include<stdio.h>
#include<stdlib.h>
void printArray(int a[], int n){ //打印数组时,需指明数组是谁,数组有多长.防止丢失数据
int i;
for (i = 0; i < n; ++i){
printf("%d “, a[i]);
}
putchar(’\n’);
}
int main(){
int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int b[10] = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
int i, tmp;
printArray(a, 10);
printArray(b, 10);
for (i = 0; i < 10; ++i){
tmp = a[i];
a[i] = b[i];//一次便利,将两个数组中所有对应元素都进行了两两交换
b[i] = tmp;
}
printArray(a, 10);
printArray(b, 10);
system(“pause”);
return 0;
}
2. 计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值
(1)从1加到10;
#include<stdio.h>
#include<stdlib.h>
int main(){
int i, sum = 0;
for (i = 1; i <= 10; ++i){
sum += i;
}
printf(”%d", sum);
system(“pause”);
return 0;
}
(2)10的阶乘;
#include<stdio.h>
#include<stdlib.h>
int main(){
int i, sum = 1;
for (i = 1; i <= 10; ++i){
sum *= i;
}
printf("%d", sum);
system(“pause”);
return 0;
}
(3)1的阶乘加到10的阶乘;
#include<stdio.h>
#include<stdlib.h>
int main(){
int i, tmp = 1,sum=0;
for (i = 1; i <= 10; ++i){
tmp = i;
sum += tmp;
}
printf("%d", sum);
system(“pause”);
return 0;
}
最终结果:
#include<stdio.h>
#include<stdlib.h>
int main(){
int i;
double tmp = 1,sum=0;
for (i = 1; i <= 100; ++i){
tmp =1.0 /i(i % 2 ? 1 : -1);
sum += tmp;
}
printf("%lf", sum);
system(“pause”);
return 0;
}
3.编写程序数一下 1到 100 的所有整数中出现多少次数字9。
分析:10位出现9或者个位出现9: (1)模10把个位取出来;(2)除10把个位去掉
#include<stdio.h>
#include<stdlib.h>
int main(){
int i, count = 0;
for (i = 1; i <= 100; ++i){
if (i % 10 == 9){
count++;
}
if (i / 10 == 9){
count++;
}
}
printf("%d", count);
system(“pause”);
return 0;
}
*扩展到1000:
#include<stdio.h>
#include<stdlib.h>
int main(){
int i, count = 0;
for (i = 1; i <= 1000; ++i){
if (i % 10 == 9){
count++;
}
if (i / 10 % 10 == 9){
count++;
}
if (i / 100 == 9){
count++;
}
}
printf("%d", count);
system(“pause”);
return 0;
}