Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

why is it that at 1500 input for sideLength the output is incorrect.

+6 votes
asked Aug 23, 2024 by EDUARDO LUEVANO DELGADO (180 points)
#include <iostream>
using namespace std;

int main() {
   int sideLength;
   int cubeVolume;
   
   cout << "Enter cube's side length: " << endl;
   cin >> sideLength;
   
   cubeVolume = sideLength * sideLength * sideLength;
   
   cout << "Cube's volume is: " << cubeVolume << endl;
   
   return 0;
}

1 Answer

0 votes
answered Aug 28, 2024 by Peter Minarik (101,420 points)
edited Aug 28, 2024 by Peter Minarik

This is a classic numeric overflow problem. int (int32 to be exact) can store 32 bits, where the minimum is -231 (-2,147,483,648) and the maximum is 231-1 (2,147,483,647).

15003 would be 3,375,000,000, which does not fit into the range of int32. It would fit into uint32 (0..232, i.e. 0..4,294,967,296), or into int64, but the point is that there is always a limit where you cannot go any higher.

You could use a floating point type (e.g. float or double) that can work with much higher numbers by trading precision. (You can check out various data type limits here.)

So, you need to make a few decisions:

  1. do you want to handle overflow cases? How? Notify the user about it or just leave it as an error case (totally acceptable for toy projects)
  2. Is precision more important, or handling huge numbers (with approximation)?
  3. Is it worth introducing a limit to the user input to handle overflows gracefully? (e.g. do not let the user enter anything larger than the cubic root of 232 for an uint type, i.e. 1,625)

Good luck!

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...