I recently started working through the "C ++ primer 5th Edition". I am currently performing the following exercise:
Exercise 1.11: Write a program that asks the user for two integers. Print each number in the range indicated by these two integers.
As a solution, I wrote the following code:
#include <iostream>
int main(){
int num1 = 0, num2 = 0;
std::cout << std::endl << "Please enter two numbers to find a range between" << std::endl;
std::cin >> num1 >> num2;
if (num1 < num2)
while (num1 <= num2){
std::cout << std::endl << num1;
++num1;
}
if (num2 < num1)
while (num2 <= num1){
std::cout << std::endl << num2;
++num2;
}
if (num1 == num2)
std::cout << std::endl << num1;
std::cout << std::endl;
However, when I enter the numbers, the output is not entirely correct;
Input Example:
Please enter two numbers to find a range betweem
>> 1 5
Output Example:
1
2
3
4
5
5
6
I do not understand that if the first input of the number I am larger than the first (for example, num1> num2), then the program produces the desired result, for example:
Please enter two numbers to find a range between
>> 5 1
1
2
3
4
5
What is particularly confusing is that when I replace the order of conditional statements, the first example will work correctly, and the second will produce the wrong output.
, , . , .
!