-
将数组A中的内容和数组B中的内容进行交换
#include <stdio.h>
#include <stdlib.h>
int main(){
int a[3] = { 2, 3, 4 };
int b[3] = { 6, 7, 8 };
int c = 0;
if (a[0] != b[0]){
c = a[0];
a[0] = b[0];
b[0] = c;
}
if (a[1] != b[1]){
c = a[1];
a[1] = b[1];
b[1] = c;
}
if (a[2] != b[2]){
c = a[2];
a[2] = b[2];
b[2] = c;
}
printf("%d %d %d\t",a[0],a[1],a[2]);
printf("%d %d %d\t", b[0], b[1], b[2]);
system(“pause”);
return 0;
}
交换两个数组的内容也可以用另外一种方法:for循环; -
计算1/1-1/2+1/3-1/4+1/5 …… + 1/99 - 1/100 的值
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int i=1;
int j;
float k = 0.0;
float x;
int n;
for (j = 1, n = 0; j < 101&& n < 100; j++,n++){
x = (pow(-1, n))*(double)i / j;
k = k + x ;
}
printf("%f\n", k);
system(“pause”);
return 0;
}
这个代码里面用到了-1的n次方根的运算 ,不太熟练的人也可以用三目运算符,还有这个代码值得注意的地方就是大家的数字要用float类型。 -
编写程序数一下 1到 100 的所有整数中出现多少次数字9
#include <stdio.h>
#include <stdlib.h>
int main()
{
int i, cout = 0;
for (i = 0; i <= 100; i++){
if (i % 10 == 9 ){
cout++;
}
if (i / 10 == 9){
cout++;
}
}
printf("%d", cout);
system("pause");
return 0;
}
用mod10=9 来确定个位数;
用/10来确定十位数;