Back to General discussions forum
My code works all fine. It's just that it breaks down with larger numbers. I don't know how to fix that appart from make the sum input larger
This is my code(C++): if someone can help me I'd really appreciate it cause I just don't see my mistake.
int main(){ int start; std::string sign; int num; uint64_t sum;
std::cout << "input data: \n"; std::cin >> start; sum = start;
while (sign!= "%"){ std::cin >> sign >> num; if (sign == "+"){ sum = sum + num; std::cout << sum << std::endl; }
else if (sign == "*"){
sum = sum * num;
std::cout << sum << std::endl;
}
}
std::cout << "num: " << num << std::endl;
sum = sum % num;
std::cout << sum;
}
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
int main(){
int start;
std::string sign;
int num;
long long sum;
std::cout << "input data: \n";
std::cin >> start;
sum = start;
while (sign!= "%"){
std::cin >> sign >> num;
if (sign == "+"){
sum = sum + num;
std::cout << sum << std::endl;
}
else if (sign == "*"){
sum = sum * num;
std::cout << sum << std::endl;
}
}
std::cout << "num: " << num << std::endl;
sum = sum % num;
std::cout << sum;
}
Your issue is not a bug (in your code) but a feature (of the problem): the out-of-the-range issues you are encountering are exactly what the problem is asking you to solve.
You might want to review some properties of modular arithmetic; for example, the lines at the top of this section:
https://en.wikipedia.org/wiki/Modular_arithmetic#Properties
Also - I just noticed - the problem itself includes a link to a very nice write-up on this very site that contains all the information you need.