我需要制作一個程式來執行以下任務:
輸入 N 個自然數。用0完成輸入。輸出最大數的數。
我已經這樣做了,你可以看到下面的代碼:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main(void) {
int i = 0, num, max_place = -1;
int max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num >= max) {
max = num;
max_place = i;
}
i ;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else printf("\nMax number was on %d place, bruh", max_place 1);
return 0;
}
然后老師讓任務變得更加困難——程式需要列印輸入數字的最大數字和下一個最大值。
我該怎么做?
uj5u.com熱心網友回復:
如果您可以使用陣列并排序,請使用這種方式。如果沒有,這在您的代碼中
int main(void) {
int i = 0, num, max_place = -1, second_max_place = -1;
int max = -2147483647;
int second_max = -2147483647;
printf("Start enter numbers, bruh (please end input with 0):\n");
scanf("%d", &num);
while (num != 0) {
if (num == 0) break;
if (num >= max) {
second_max = max;
second_max_place = max_place;
max = num;
max_place = i;
}
if(num < max && num >= second_max){
second_max = num;
second_max_place = i;
}
i ;
scanf("%d", &num);
}
if (max_place == -1) printf("Numbers were not entered");
else{
printf("\nMax number was on %d place, bruh", max_place 1);
printf("\nSecond Max number was on %d place, bruh", second_max_place 1);
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/336486.html
下一篇:在voidfunc()中回傳結構
