It's a c++ question

Asked 2 years ago, Updated 2 years ago, 22 views

I want to use the function to find the sum of n, the sum of even numbers up to n, and the sum of odd numbers. Implemented within a function, the main function is output only. When I run it, it says that I am using the uninitialized regional variables i,s,r. Please check if the direction I am coding matches the direction I want. Please give me your advice on how to fix it.

c++

2022-09-20 19:45

2 Answers

It's a code where you can feel deep anguish.

Please refer to the code below.

#include<iostream>
using namespace std;
void sum(int n, int* nsum, int* esum, int* osum);

int main()
{
    int nsum = 0, esum = 0, osum = 0;
    int n = 0;

    cin >> n;

    sum(n, &nsum, &esum, &osum);

    cout << "1 to n sum: " << nsum << endl;
    cout << "The sum of even numbers from 1 to n: " << esum << endl;
    cout <<"The sum of odd numbers from 1 to n: "<< osum << endl;

    return 0;
}

void sum(int n, int* nsum, int* esum, int* osum)
{
    *nsum = 0;
    *esum = 0;
    *osum = 0;

    for (int i = 1; i <= n; i++)
    {
        (*nsum) += i;

        if (i % 2 == 1)
            (*osum) += i;
        else
            (*esum) += i;
    }
}


2022-09-20 19:45


2022-09-20 19:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.