c語言中實現(xiàn)數(shù)組幾個數(shù)求次大值
更新時間:2022年12月05日 15:45:42 作者:zwmonkey
這篇文章主要介紹了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;//設置最大值下標為0,為數(shù)組第一個數(shù) int second_subscript = 1;//設置次大值下標為1,為數(shù)組第二個數(shù) while (1) { for (int i = 0; i < len;i++)//從下標1(即第二個元素開始遍歷)開始遍歷 { if (max_subscript == i) { continue;//跳過原來最大值的下標,直接開始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("最大值下標max_subscript=%d,次大值下標second_subscript=%d\n", max_subscript, second_subscript); getchar(); return 0; }
c語言輸出數(shù)組中最大值和次大值
本題主要的得分點在怎么求數(shù)組中的最大值和次大值,方法有很多,最常見的就是對數(shù)組進行排序,可以很輕松得到最大值和次大值。本題采用另外一個思路,第一次先在數(shù)組中找到最大值,第二次查找剩下的最大值(排除掉最大值,不是刪除)
另外比較困擾的一點就是怎么直接從帶空格的輸入中直接得到整型數(shù)字,而不是像本題一樣先當字符串去接收,然后從字符串中轉數(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)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C++實現(xiàn)LeetCode(150.計算逆波蘭表達式)
這篇文章主要介紹了C++實現(xiàn)LeetCode(150.計算逆波蘭表達式),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-07-07C++ 數(shù)據(jù)類型強制轉化的實現(xiàn)
這篇文章主要介紹了C++ 數(shù)據(jù)類型強制轉化的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-02-02將正小數(shù)轉化為2-9進制小數(shù)的實現(xiàn)方法
本篇文章對正小數(shù)轉化為2-9進制小數(shù)的實現(xiàn)方法進行了介紹,需要的朋友參考下2013-05-05