Question: How do I determine the ratio of two cin-ed integers?

I'm writing a simple mathematical map for the user's two inputted numbers.

Any idea how to create code to determine the ratio of two numbers?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include "std_lib_facilities.h"

int main()
{
	cout<<"Hey there, give me two numbers please.\n";
		int v1;
		int v2;
			cout<<"First value please...\n";
			cin>>v1;
			cout<<"Second value please...\n";
			cin>>v2;
				cout<<"You've chosen v1("<<v1<<") and v2("<<v2<<").\n\n\n";
			
			cout<<"Now for some mathematical magic.\n";
			cout<<"Which is greater?\n";
				if (v1>v2){
					cout<<v1<<" is GREATER than "<<v2<<".\n";
				}
				if (v1<v2){
					cout<<v1<<" is LESS than "<<v2<<".\n";
				}
			cout<<v1<<" + "<<v2<<" = ";
			cout<<v1+v2<<"\n";
			cout<<v1<<" - "<<v2<<" = ";
			cout<<v1-v2<<"\n";
			cout<<v1<<" * "<<v2<<" = ";
			cout<<v1-v2<<"\n:";
}
The divide operator takes its type from the left hand operand - to get a floating point divide you need to convert

double(v1)/v2

@mik2716, do you mean this for the ratio?
Use double instead of int to store the users values. You must also use:

cout.precision(5);

so cout will display data from the double.

This works:
1
2
3
4
5
6
7
8
9
10
11
double a = 6, b = 4;
double result;


int main(){
 result = (a/b);
 cout.precision(7);
 cout << result;


}



This will drop everything after your decimal because you supplied ints.(i.e. if answer is 1.5 it will be stored as 1)

1
2
3
4
5
6
7
8
9
10
11
int a = 6, b = 4;
double result;


int main(){
 result = (a/b);
 cout.precision(7);
 cout << result;


}
Last edited on
Just use

 
cout << "v1/v2 = " << double(v1)/v2


to output the ratio

How it works:

/ is a bit of a weird operator. There are two versions: integer divide and floating point divide.

Suppose you had int v1=3 and int v2=2 then v1/v2 would give 1 (not 1.5) (since the output is an integer). So to get a floating point result you need to force a conversion. The double(v1) part converts v1 from int to double. Then the / operator sees a double on its left hand side and so uses floating point divide. Floating point divide must have floating point inputs, so v2 is automatically converted to a double as well.


@mik2718,

Thanks! The details really help me understand.

@pata,

Thanks for your input as well. I will try them both.

Topic archived. No new replies allowed.