Explain my output

Nov 14, 2012 at 2:43am
HI, this is my code,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;

int main(){
	double x,y;
	int quotient;

	char choice = 'X';

	while(toupper(choice) != 'E'){
		cout<<"Enter the value of x: ";
		cin>> x;
		cout<<"Enter the value of y: ";
		cin>> y;
		quotient = x/y;

		cout <<x<<" "<<y<<" "<<quotient;
		cout<< "Enter E to exit";
		cin>> choice;
	}
	return 0;
}



Can someone explain to me when the value of x=5 and y=2, the output is 2?
Simmilar,

x=6, y=3....output ans is 3
x=19, y=2....output ans is 9

Is it because I declare quotient as int and the number is rounded off to a whole?
Nov 14, 2012 at 3:37am
When you write x/y with both x and y integers, you are doing integer division. This truncates the fractional portion of any result you get. Thus, 5/2=2.5 truncates to 2 and 19/2=9.5 truncates to 9. I can't explain the other result though...are you sure you read it correctly?
Nov 14, 2012 at 4:05am
quotient is declared as an integer. It should be a double as well since x and y are doubles. Even if x and y aren't being converted to ints before the division, the answer is being forced into one so you are losing anything after the decimal.
Last edited on Nov 14, 2012 at 4:05am
Topic archived. No new replies allowed.