(E) Cube

Goal: I will take an even closer look at the behavior of integers in C++. I will learn to detect overflow.

Instructions: In the previous exercises you were provided with a ready-made code template and a project file in Git repository. You will not receive a ready code template in all of the exercises on this course. Instead, you should also be able to create a new project in Qt Creator.

In this assignment, you will create the project by yourself. You need to save the project in the directory with exactly the correct name in order to allow the automatic evaluation system to find it when you submit your solution to the course platform. Save your project in the directory student/02/cube located in the data repository. Please note that if you start by creating the project in Qt Creator under the name cube, Qt Creator will save the project files in a directory called cube defined in the window Project Location. This means you won’t have to create a separate directory called cube under the directory student/02.

Later on, the first paragraph of the assignment will tell you whether to use a template or create the project yourself, and what the directory should be called.

Assignment: Create a program that calculates the cube of a non-negative integer (or raises the integer to the third power) and prints the result or, if there is an overflow in the calculation, an error message.

Set int as the type of the input and all of the other variables, although it is sufficient that the program works with non-negative numbers. The program should work like the examples below:

Enter a number: 2
The cube of 2 is 8.
Enter a number: 100000
Error! The cube of 100000 is not -1530494976.
Enter a number: 200000000
Error! The cube of 200000000 is not 134217728.

Tips for completing the assignment:

  • The latter number in the error message (”is not …”) is the result of the calculation performed with variables of the type int.
  • C++ has no such operator as the Python’s operator **. The simplest way to calculate the cube is by performing two multiplications.
  • C++ does have the function pow, which you can use if you want to practice the use of the libraries. The function in question is located in the library cmath, which you have to include using the directive include.
  • C++ also has the operator ^, but this should not be used here as it will not raise the integer to the higher power but instead perform a bitwise XOR operation.
  • As you can see in the third example run, with a big enough input value, the result of the calculation is not a negative but a positive number. Therefore, it is not enough for you to check whether the resulting number is positive. Think back to how your old math teacher told you to check your answers in a math test. You can use the same trick to check your results here.

A+ presents the exercise submission form here.