1.使用printf()时不要用取地址符
2.计算前n项和:在for循环中:
sum+=item;
flag=……;//符号正负的变化
a=……;//分子的变化
denominator=……;//分母的变化
item=flag*a/denominator;
3.计算分式时:(这里默认int denominator)
item=1.0/denominator;
//item=1/denominator;输出的结果是错的,分子分母必须有一个是浮点数
4.计算4个整数的和,平均值
法一:适用于知道要输入的数字的个数,且个数较多的情况
#include<stdio.h>
int main() {
int i = 0;
int num = 0, sum = 0;
double average = 0;
for (i = 1;i <= 4;i++) {
scanf("%d", &num);
sum += num;
}
average = sum / 4;
printf("sum=%d,average=%.1lf", sum, average);
return 0;
}
法二:适用于知道要输入的数字的个数,且个数较少的情况;
#include<stdio.h>
int main() {
int num1 = 0, num2 = 0, num3 = 0, num4 = 0;
int sum = 0;
double average = 0;
scanf("%d %d %d %d", &num1, &num2, &num3, &num4);
sum = num1 + num2 + num3 + num4;
average = sum / 4;
printf("Sum = %d; Average = %.1lf", sum, average);
return 0;
}
5.计算组合数
#include<stdio.h>
double fact(int m, int n);
int main() {
int m =0, n = 0;
double result = 0;
scanf("%d %d", &m, &n);
result = fact(m, n);
printf("result = %.0lf", result);//使最后的组合数为整数
return 0;
}
double fact(int m, int n) {
double result=0;
int i = 0;
double a = 1, b = 1,c = 1;//a,b,c分别代表m,n,(n-m)的阶乘
for (i = m;i >=1;i--) {
a *= i;
}
for (i = n;i >=1;i--) {
b *= i;
}
for (i = n-m;i >=1;i--) {
c *= i;
}
result = b/a/c;
return result;
}
6.本题要求将输入的任意3个整数从小到大输出。
#include<stdio.h>
int main() {
int a = 0, b = 0, c = 0;
int max=0,middle=0,min=0;
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
if (b > c) {
max = a;
middle = b;
min = c;
}
else if (b < c) {
if (c > a) {
max = c;
middle = a;
min = b;
}
else {
max = a;
middle = c;
min = b;
}
}
}
else {
if (a > c) {
max = b;
middle = a;
min = c;
}
else {
if (c > b) {
max = c;
middle = b;
min = a;
}
else {
max = b;
middle = c;
min = a;
}
}
}
printf("%d->%d->%d", min, middle, max);
return 0;
}