Description
有n个整数,把它们存放到一个一维数组中(下标从0开始),通过指向数组的指针变量的移动遍历整个数组,找出数组的最大数和它的下标并输出。
Input
输入数据有多组,每组占一行,第一个数n(10≤n≤20)表示该组测试数据的个数,后面跟有n个整数。若n=0,表示输入结束,不需处理。
Output
对于每组输入,输出单独占一行,输出包括最大数及其下标,中间用空格分隔。
Sample Input
12 5 3 15 4 12 54 32 53 42 20 4 23
10 1 2 3 4 5 6 7 8 9 10
0
Sample Output
54 5
10 9
#include<stdio.h>
#include<stdlib.h>
//定义函数实现查找最大值,并返回最大值的下标
int num_search(int *num,int n)
{
int *num_s;
num_s=num;
int i,k;
int max=num[0];
for(i=0;i<n;i++)
{
if(*(num_s+i)>max)
{
max=*(num_s+i);
k=i;
}
}
return k;
}
int main()
{
int n,max_subscript;
scanf("%d",&n);
while(n!=0)
{
int i;
//malloc()函数实现申请储存n个整型变量的数组
int *num=(int *)malloc(sizeof(int)*n);
//使用循环语句为数组赋值
for(i=0;i<n;i++)
{
scanf("%d",&num[i]);
}
max_subscript=num_search(num,n);
printf("%d %d\n",num[max_subscript],max_subscript);
free(num);
scanf("%d",&n);
}
return 0;
}
malloc()函数就是申请了个空间,或者你写成 num[n];应该也会编译通过
看不懂malloc()函数的话,欢迎通过我的博客进行学习 嘿嘿嘿
快期末考试了 加油加油
供参考:
#include<stdio.h>
#define N 21
int main()
{
int n,a[N],*p,max,max_i;
while (scanf("%d", &n)==1 && n != 0){
for (p = a; p < a + n; p++)
scanf("%d", p);
for (p = a,max = *p,max_i = 0; p < a + n; p++){
if (max < *p){
max = *p;
max_i = p - a;
}
}
printf("%d %d\n",max, max_i);
}
return 0;
}