vendredi 26 novembre 2021

How can I access variables from inside an if statement in C++?

Here's the code I had made:

#include <iostream>

int main()
{
    int num1, num2, num3, num4, num5, useNumber1, useNumber2, useNumber3, useNumber4, useNumber5;
    std::cout << "Give me a string of 5 integers! I'll determine the sum of the positive integers.\n";
    std::cin >> num1 >> num2 >> num3 >> num4 >> num5;
    if (num1 > 0) {
        useNumber1 = num1;
    }
    if (num2 > 0) {
        useNumber2 = num2;
    }
    if (num3 > 0) {
        useNumber3 = num3;
    }
    if (num4 > 0) {
        useNumber4 = num4;
    }
    if (num5 > 0) {
        useNumber5 = num5;
    }
    int finalNumber = useNumber1 + useNumber2 + useNumber3 + useNumber4 + useNumber5;
}

For some reason, whenever I run the code and place a negative number in, let's say, num5, an error pops up telling me that useNumber5 was inactive or something similar. Is there a fix for thism or do I have to change my code completely?

Aucun commentaire:

Enregistrer un commentaire