简体   繁体   中英

c++, 'avg = sum/5' gives me junk values but writing avg = sum/2 gives works and i don't know why

I'm trying to create a simple program with c++. that calculates the average of 5 numbers that the user inputs but it keeps giving me a junk value when i run it. I've spent over 30 minutes messing with this trying to fix it but i can't seem to figure it out.

#include <iostream>  

int main() {
    std::cout << "hello this my program" << '\n';
    int sum, avg;

    int numbOne{  }, numbTwo{  }, numbThree{  }, numbFour{  }, numbFive{  };
    std::cout << "enter your first number: ";
    std::cin >> numbOne;

    std::cout << "enter your second number: ";
    std::cin >> numbTwo;

    std::cout << "enter your third number: ";
    std::cin >> numbThree;

    std::cout << "enter your fourth number: ";
    std::cin >> numbFour;

    std::cout << "enter your fifth number:";
    std::cin >> numbFive;

    sum = numbOne+numbTwo+numbThree+numbFour+numbFive;

    avg = sum/5;

    std::cout << "the average is: " << avg << '\n;';
}

this is what gets printed in console.

hello this my program
enter your first number: 1
enter your second number: 2
enter your third number: 3
enter your fourth number: 4
enter your fifth number:5
the average is: 32619

This is why: '\\n;' I'm sure you meant to put double quotes.. Or a if you use single, '\\n' followed by ';' ..

So it should be: "\\n"; or '\\n';

As pointed out in the comments, you should enable your compiler warnings like -Wall and -Wextra . They will help you see the problem -Wmultichar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM