Code for Task 14 not working

Back to General discussions forum

PeachyBeach     2022-09-27 12:10:05

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.

include <iostream>

include <vector>

include <string>

include <cmath>

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;

}

PeachyBeach     2022-09-27 12:11:05
    #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;


    }
zelevin     2022-09-27 14:08:48

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.

Please login and solve 5 problems to be able to post at forum