+ 3
Transportation C++
/* How to calculate the number of buses i need to transport people? if I enter the number 165, it outputs 3 although it should be 4 */ #include <iostream> using namespace std; int main() { int bus_max = 50; int passengers; int last_bus; int buses; int free_places; cout << "Enter the number of passengers: "; cin >> passengers; last_bus = passengers % bus_max; cout << "Last bus will take " << last_bus << " passengers." << endl; free_places = bus_max - last_bus; cout << free_places << " free seats will remain." << endl; buses = passengers / bus_max; cout << "It will take " << buses << " buses to transport " << passengers << " people." << endl; system("PAUSE"); return 0; }
3 Antworten
+ 3
That is because C++ rounds down by default when you divide. You can use functions such as round() and ceil() in <cmath> and <math.h> relatively, to round up, but a simple if statement will also work:
if(last_bus > 0)
buses++;
So this code works fine:
#include <iostream>
using namespace std;
int main() {
int bus_max = 50;
int passengers;
int last_bus;
int buses;
int free_places;
cout << "Enter the number of passengers: ";
cin >> passengers;
last_bus = passengers % bus_max;
cout << "Last bus will take " << last_bus << " passengers." << endl;
free_places = bus_max - last_bus;
cout << free_places << " free seats will remain." << endl;
buses = passengers/bus_max;
if(last_bus > 0)
buses++;
cout << "It will take " << buses << " buses to transport " << passengers << " people." << endl;
system("PAUSE");
return 0;
}
+ 3
many thanks!
+ 1
Aleksei Radchenkov explained it well, but I want to dig a little deeper, because C++ doesn't actually round down the result of the division (of integers):
Every CPU (or at least most of them) can deal with 2 kind of numbers: those written in "binary" (integers) and those written in "scientific notation" (floating-point numbers)
When doing operations on integers it gives an integer;
when doing operations with floating-point numbers it gives a floating-point number
So, when doing a division of integers, it performes the Euclidean division (the one with quotient and reminder)
which result tells how many times does A fit in B,
never the "real" division (A times the multiplicative inverse of B) which is performed only on floating-point numbers