编写一个函数,功能为求三个数的平均值。
编写一个函数,功能为求三个数的平均值。
函数:
double average(double a, double b, double c) {
return (a + b + c) / 3.0;
}
例子:
#include <stdio.h>
double average(double a, double b, double c) {
return (a + b + c) / 3.0;
}
int main() {
double a = 1.2, b = 2.3, c = 3.4;
double avg = average(a, b, c);
printf("三个数 %.1f, %.1f, %.1f 的平均值是 %.2f\n", a, b, c, avg);
return 0;
}
float average(float a, float b, float c) {
float avg = (a + b + c) / 3.0;
return avg;
}
float averageFun(float a, float b, float c) {
float avg = (a + b + c) / 3.0;
return avg;
}
//输入三个字符串,按由小到大的 顺序输出,用指针来实现
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define M 5
int main()
{
char a[M], b[M], c[M];
char *p, *q, *t;
char x[M];
printf("请输入三个字符串:\n");
gets(a);
gets(b);
gets(c);
p = a; // abc
q = b; // agf
t = c; // ccc
// printf("输出%d\n", strcmp(p, q)); // 输出-1 说明 p比q小
// printf("strcmp(q,p) 输出%d\n", strcmp(q,p)); // 输出1 说明 q比p 大
if ((strcmp(p, q)) > 0) // p 比 q 大,交换 pq的值,让小的放前面
{
strcpy(x, p); // 将p的值覆盖到x里面,
strcpy(p, q); // 将q的值覆盖到p
strcpy(q, x); // 将x的值覆盖到q
}
if ((strcmp(p, t)) > 0) // p > t ? 同上,x相当于 temp 辅助交换
{
strcpy(x, p);
strcpy(p, t);
strcpy(t, x);
}
if ((strcmp(q, t)) > 0) // q > t
{
strcpy(x, q);
strcpy(q, t);
strcpy(t, x);
}
printf("输出由小到大排序好的三个字符串:%s\t%s\t%s\n", p, q, t);
return 0;
}
result:
请输入三个字符串:
ccc
abf
acb
输出由小到大排序好的三个字符串:abf acb ccc
//输入三个字符串,按由小到大的 顺序输出,用指针来实现
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define M 5
int main()
{
char a[M], b[M], c[M];
char *p, *q, *t;
char x[M];
printf("请输入三个字符串:\n");
gets(a);
gets(b);
gets(c);
p = a; // abc
q = b; // agf
t = c; // ccc
// printf("输出%d\n", strcmp(p, q)); // 输出-1 说明 p比q小
// printf("strcmp(q,p) 输出%d\n", strcmp(q,p)); // 输出1 说明 q比p 大
if ((strcmp(p, q)) > 0) // p 比 q 大,交换 pq的值,让小的放前面
{
strcpy(x, p); // 将p的值覆盖到x里面,
strcpy(p, q); // 将q的值覆盖到p
strcpy(q, x); // 将x的值覆盖到q
}
if ((strcmp(p, t)) > 0) // p > t ? 同上,x相当于 temp 辅助交换
{
strcpy(x, p);
strcpy(p, t);
strcpy(t, x);
}
if ((strcmp(q, t)) > 0) // q > t
{
strcpy(x, q);
strcpy(q, t);
strcpy(t, x);
}
printf("输出由小到大排序好的三个字符串:%s\t%s\t%s\n", p, q, t);
return 0;
}