Recently one of my beginner C++ developers-friends showed me a non-industrial piece of code where he wanted to learn entities of loops, std::cin
, and std::cout
concepts. Let me introduce a problem briefly.
He has to enter via std::cin
the number of numbers that he needs to insert from the keyboard in order to count the average of that numbers. Here is the code(please do not be critical to the code).
#include <iostream>
int main ()
{
int amount = 0;
std::cout << "Please insert amount of numbers you want to enter"<<'\n';
std::cin >> amount;
std::cout << "You have to enter "<< amount <<" numbers"<<'\n';
if (amount < 1){
std::cout << "You entered invalid number" << '\n';
std::cout << "Average is "<< 0.0 <<'\n';
}
else{
float current = 0.0;
float total_sum = 0.0;
for ( int i = 1; i <= amount; ++i){
std::cout << "Insertion " << i <<": Please enter any number" << '\n';
std::cin >> current;
total_sum += current;
}
std::cout << "Average is " << total_sum/amount << '\n';
}
return 0;
}
The code works fine when we insert integer values via std::cin
for the amount
variable, but whenever we enter any floating-point number for amount
the code starts doing strange things. For example here is the behavior when I inserted 3.14
Please insert amount of numbers you want to enter
3.14
You have to enter 3 numbers
Insertion 1: Please enter any number
Insertion 2: Please enter any number
I even checked for extra convenience what value will be assigned to amount
in such cases, and the result is predictable that it will narrow the value and assign it to the variable. Unfortunately, I couldn't find an explanation to this issue and hope I can do it with your assistance.