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

ผลรวมค่า ASCII ของแต่ละคำในประโยค ในภาษา C

โจทย์ให้คำนวณผลรวมค่า ASCII ของตัวอักษรในแต่ละคำของประโยค แล้วนำมารวมกันเป็นผลรวมทั้งหมด

ตัวอย่าง

ประโยค: "I love tutorials point"

Output: 105 438 999 554 2096

(105=I, 438=love, 999=tutorials, 554=point, 2096=รวมทั้งหมด)

โค้ดตัวอย่าง (C++)

#include <iostream>
#include <string>
#include <vector>
using namespace std;

long long sumCalc(string str, vector<long long> &arrSum) {
    int len = str.length();
    int sum = 0;
    long long total = 0;
    for (int i = 0; i < len; i++) {
        if (str[i] == ' ') {
            total += sum;
            arrSum.push_back(sum);
            sum = 0;
        } else {
            sum += str[i];
        }
    }
    arrSum.push_back(sum);
    total += sum;
    return total;
}

int main() {
    string str = "i love tutorials point";
    vector<long long> arrSum;
    cout << "The string is " << str << endl;
    long long total = sumCalc(str, arrSum);
    cout << "Sum of ASCII values: ";
    for (auto x : arrSum) cout << x << " ";
    cout << endl << "Total sum -> " << total;
    return 0;
}

ผลลัพธ์

The string is i love tutorials point
Sum of ASCII values: 105 438 999 554
Total sum -> 2096