c語言中實現(xiàn)數(shù)組幾個數(shù)求次大值
c語言數(shù)組幾個數(shù)求次大值問題
#include<stdio.h>
int main()
{
int a[] = { 7, 4, 9, 9, 6 };
int len = sizeof(a) / sizeof(int);//求數(shù)組元素個數(shù)
int max_subscript = 0;//設(shè)置最大值下標(biāo)為0,為數(shù)組第一個數(shù)
int second_subscript = 1;//設(shè)置次大值下標(biāo)為1,為數(shù)組第二個數(shù)
while (1)
{
for (int i = 0; i < len;i++)//從下標(biāo)1(即第二個元素開始遍歷)開始遍歷
{
if (max_subscript == i)
{
continue;//跳過原來最大值的下標(biāo),直接開始i+1的循環(huán)
}
if (a[i]>a[max_subscript])//遍歷的值a[i]比最大值都大那么此時的最大值為a[i],次大值為原來的最大值即a[max_subscript]
{
second_subscript = max_subscript;//先賦值次大值為原來的最大值
max_subscript = i;//賦值現(xiàn)在的最大值為a[i]
}
else
{
/*即a[i]小于最大值最大值得情況,那么就有兩種情況:
1.a[i]大于次大值,那么
此時最大值還是原來的最大值a[max_subscript],次大值a[second_subscript]變?yōu)閍[i]
2.a[i]小于次大值,那么 原來的最大值 和次大值都不改變
*/
if (a[i] > a[second_subscript])
{
second_subscript = i;
}
}
}
if (a[max_subscript] != a[second_subscript])
{
break; //最大值和次大值不相等就跳出循環(huán),
}
a[second_subscript] = 0;//相等就把次大值得值重置為0
}
printf("最大值a[max_subscript]=%d,次大值a[second_subscript]=%d\n", a[max_subscript], a[second_subscript]);
printf("最大值下標(biāo)max_subscript=%d,次大值下標(biāo)second_subscript=%d\n", max_subscript, second_subscript);
getchar();
return 0;
}
c語言輸出數(shù)組中最大值和次大值

本題主要的得分點在怎么求數(shù)組中的最大值和次大值,方法有很多,最常見的就是對數(shù)組進行排序,可以很輕松得到最大值和次大值。本題采用另外一個思路,第一次先在數(shù)組中找到最大值,第二次查找剩下的最大值(排除掉最大值,不是刪除)
另外比較困擾的一點就是怎么直接從帶空格的輸入中直接得到整型數(shù)字,而不是像本題一樣先當(dāng)字符串去接收,然后從字符串中轉(zhuǎn)數(shù)字保存到另外的一個整型數(shù)組中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <ctype.h>
int main()
{
// please write your code here
char oriInput[200] = {0};
int inputInt[100] = {0};
fgets(oriInput,200,stdin);
int len = strlen(oriInput);
int i=0,k=0;
int fimax=0,semax=0;
char *pStart = oriInput;
for(i=0; i<len; i++)
{
if(oriInput[i] == ' ')
{
oriInput[i] = '\0';
inputInt[k++] = atoi(pStart);
pStart = &oriInput[i+1];
}
}
inputInt[k] = atoi(pStart);
for(i=0; i<=k; i++)
{
if(fimax < inputInt[i])
fimax = inputInt[i];
}
for(i=0; i<=k; i++)
{
if(semax < inputInt[i] && inputInt[i] != fimax)
semax = inputInt[i];
}
if(fimax == semax)
semax = 0;
printf("%d %d",fimax,semax);
return 0;
}以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C++項目基于HuffmanTree實現(xiàn)文件的壓縮與解壓縮功能
這篇文章主要介紹了C++項目基于HuffmanTree實現(xiàn)文件的壓縮與解壓縮功能,本文給大家提到文件壓縮的概念介紹及壓縮方法,通過示例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-08-08
VS2022新建項目時沒有ASP.NET Web應(yīng)用程序(.NET Framework)
本文主要介紹了VS2022新建項目時沒有ASP.NET Web應(yīng)用程序的解決,文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-10-10
C語言實現(xiàn)通訊管理系統(tǒng)設(shè)計
這篇文章主要為大家詳細(xì)介紹了C語言實現(xiàn)通訊管理系統(tǒng)設(shè)計,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01

