用 C++ 找出隱藏數字的程式
在這個問題中,有一個包含 n 個整數值的陣列 arr[]。我們的任務是用 C++ 建立一個程式來找出隱藏的數字。
程式碼描述 − 對於一個數組,隱藏數字是指當此數字減去陣列的每個元素時,所得和為 0。
舉個例子來理解這個問題:
輸入
arr[] = {4, 1, 6, 7, 2}
輸出
4
從陣列的所有元素中減去 4。然後再相加
= (1 - 4) + (6 - 4) + (7 - 4) + (4 - 2) = -3 + 2 + 3 - 2 = 0
解決方案方法
要解決這個問題,我們需要計算陣列中所有元素的總和。然後將總和除以陣列中元素的總數。如果和/(元素數)的值是整數,則它是隱藏的數字。
程式演示我們解決方案的工作原理:
示例
#include <iostream> using namespace std; int calcHiddenNumber(int arr[], int n){ long int sum = 0; for(int i = 0; i < n; i++){ sum = sum + arr[i]; } int hidNum = (sum / n); if((hidNum * n) == sum ) return hidNum; else return -1; } int main() { int n = 4; int arr[] = { 4, 11, 12, 21 }; cout<<"The hidden number for the array is "<<calcHiddenNumber(arr, n); return 0; }
輸出
The hidden number for the array is 12
廣告