這是我老師給我的問題
撰寫一個 C 程式,將 10 個整數存盤在一個大小為 10 的陣列中,并顯示該陣列的內容。用 1 替換陣列中最高的 5 個數字,用 0 替換最低的 5 個數字,并顯示新陣列的內容。[例如原始陣列 44 11 6 99 30 78 32 31 66 55 新陣列 1 0 0 1 0 1 0 0 1 1
我一整天都在這個問題上掙扎:(
uj5u.com熱心網友回復:
有很多方法可以解決這個問題。一個好方法是將陣列排序到另一個陣列中,然后用 0 替換第一半,用 1 替換后半,如下所示:
#include<stdio.h>
int main(){
const int arraySize = 10;
int i, j;
int arr[arraySize];
int arrSorted[arraySize];
int temp;
// Get input from user
printf("Please enter 10 numbers!\n");
for (i = 0; i < arraySize; i )
{
scanf("%d", &arr[i]);
// Copy array into another to sort it later
arrSorted[i] = arr[i];
}
// Print input
printf("Input: ");
for (i = 0; i < arraySize; i )
{
printf("= ", arr[i]);
}
printf("\n");
//Sort the array in ascending order
for (i = 0; i < arraySize; i )
{
for (j = i 1; j < arraySize; j )
{
if(arrSorted[i] > arrSorted[j])
{
temp = arrSorted[i];
arrSorted[i] = arrSorted[j];
arrSorted[j] = temp;
}
}
}
// Start replacing procedure
for (i = 0; i < arraySize; i )
{
for (j = 0; j < arraySize; j )
{
if (arr[j] == arrSorted[i])
{
if (i < arraySize / 2) // Replace 1st half with 0s
{
arr[j] = 0;
}
else // Replace 2nd half with 1s
{
arr[j] = 1;
}
break;
}
}
}
// Print result
printf("Result: ");
for (i = 0; i < arraySize; i )
{
printf("= ", arr[i]);
}
printf("\n");
return 0;
}
當然,如果你不想自己排序,也可以使用 C 標準庫 qsort() 函式。
另一種解決方案是,找到陣列的中位數,然后用 0 替換任何小于它的數字,用 1 替換任何大于它的數字。盡管使用這個解決方案會有一些關于如何處理中位數本身的挑戰如果有多個中位數(重復)怎么辦?
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/335266.html
