Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ หาหลักแรกของผลคูณอาร์เรย์


หาหลักแรกของผลคูณสมาชิกทั้งหมดในอาร์เรย์

ตัวอย่าง: arr = {12, 5, 16} → ผลคูณ = 960 → หลักแรก = 9

ตัวอย่างโค้ด

#include <bits/stdc++.h>
using namespace std;

int calc_1digit(int arr[], int x) {
    long long int prod = 1;
    for(int i = 0; i < x; i++) prod = prod * arr[i];
    while (prod >= 10) prod = prod / 10;
    return prod;
}

int main() {
    int arr[] = {12, 43, 32, 54};
    cout << "The first digit will be: " << calc_1digit(arr, 4) << endl;
}

ผลลัพธ์

The first digit will be: 8