C++ program to calculate the sum of all five-digit odd numbers? -
i'm having problem following simple code, don't know why output become negative... program supposed calculate sum of odd , five-digit numbers 10001, 10003, 10005, etc.
#include <iostream> using namespace std; int main() { int num, sum = 0; (num = 10001 ; num <= 99999 ; num+=2){ sum += num; } cout << num << " " << sum; return 0; }
it means there overflow of type int. type can not represent sum. advice declare variable sum like
long long int sum = 0;
after can compare result maximum value stored in type int. example
#include <limits> //... std::cout << std::numeric_limits<int>::max() << " " << sum << std::endl;;
Comments
Post a Comment