C++ 程式碼,用於減小陣列中偶數值


假設有一陣列 'arr',大小為 n,包含正整數。我們必須查詢偶數並將其減小 1。完成此流程後,我們打印出陣列。

因此,如果輸入類似 n = 7,arr = {10, 9, 7, 6, 4, 8, 3},那麼輸出將是 9 9 7 5 3 7 3。

步驟

要解決此問題,我們將遵循以下步驟 -

for initialize i := 0, when i < n, update (increase i by 1), do:
   if arr[i] mod 2 is same as 0, then:
      (decrease arr[i] by 1)
   print(arr[i])
print a new line

示例

讓我們看看以下實現,以獲得更好的理解 -

#include <bits/stdc++.h>
using namespace std;
#define N 100
void solve(int n, int arr[]) {
   for (int i = 0; i < n; i++){
      if (arr[i] % 2 == 0)
         arr[i]--;
      cout<< arr[i] << " ";
   }
   cout<< endl;
}
int main() {
   int n = 7, arr[] = {10, 9, 7, 6, 4, 8, 3};
   solve(n, arr);
   return 0;
}

輸入

7, {10, 9, 7, 6, 4, 8, 3}

輸出

9 9 7 5 3 7 3

更新於:2022 年 3 月 29 日

239 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.