C语言设计 (第四版) 谭浩强 习题2.4(2)
习题 2.4(2)依次将10个数输入,要求输出其中最大的数。
IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。
代码块
方法1: 使用选择排序将最大数调整到数组第1个,然后输出
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num[10], temp;
for(int i = 0; i < 10; i++) {
scanf_s("%d", &num[i]);
}
for(int i = 0; i < 9; i++){
for(int j = i + 1; j < 10; j++){
if(num[i] < num[j]){
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
printf("Max = %d\n", num[0]);
system("pause");
return 0;
}
方法2:设定max,然后与数组一一比较。
#include <stdio.h>
#include <stdlib.h>
int main()
{
int num[10];
int max = 0;
for(int i = 0; i < 10; i++) {
scanf_s("%d", &num[i]);
}
for(int i = 0; i < 10; i++){
if(num[i] > max){
max = num[i];
}
}
printf("Max = %d\n", max);
system("pause");
return 0;
}
方法3: 使用指针、函数的模块化设计
#include <stdio.h>
#include <stdlib.h>
#define N 10 //定义输入数的个数
#define FORMAT1 "%d" //定义输出格式符,匹配输入类型
#define FORMAT2 "Max = %d\n" //定义输出格式符,匹配输出格式
typedef int Type; //定义可变类型,不一定是整型
//输入函数
void input(Type *arr, int n){
for(Type *p = arr; p < arr + n; p++){
scanf_s(FORMAT1, p);
}
}
//求最大数函数
Type Max(Type *arr, int n){
Type max = 0;
for(Type *p = arr; p < arr + n; p++){
if(*p > max){
max = *p;
}
}
return max;
}
int main(){
Type *arr = (Type*)malloc(N * sizeof(Type));
input(arr, N);
printf(FORMAT2, Max(arr, N));
free(arr);
system("pause");
return 0;
}