C //习题 2.4(2)依次将10个数输入,要求输出其中最大的数。

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;
}
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值