How to get 2 divided numbers printed on screen?

Hi everyone,

Im fresh to the programming world and would like to ask a question.

I need to make a program that should have 10 declared variables from appropriate type and later on i need to assign those 10 variables with these values:
200, -100, 15.123, 15.56789, T, true, “true”, 2/5, 1/4, a.

I managed to get all of these printed on screen except 2/5 and 1/4 i got zero printed on screen for those two.
Is it wrong that use float for those two numbers or am i doing something else wrong?

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
29
30
31
32
33
34
35
#include <iostream>
#include <string>
using namespace std;
int main ()
{
	int a, b;
	float c, d, e, f;
	char letter, letter1;
	string word, word1;
	
	a=200;
	b=-100;
	c=15.123;
	d=15.56789;
	e=2/5;
	f=1/4;
	letter='T';
	letter1='a';
	word="true";
	word1="\"true\"";
	
	cout<<a<<endl;
	cout<<b<<endl;
	cout<<c<<endl;
	cout<<d<<endl;
	cout<<letter<<endl;
	cout<<word<<endl; 
	cout<<word1<<endl;
	cout<<e<<endl;
	cout<<f<<endl;
	cout<<letter1<<endl;

	return 0;
	
}
Hello kakoda,

Welcome to the forum.

First off I would change the "float" to "double". The double has greater precision than a float and will store the number better. These days "double" is the preferred floating point type for variables.

On lines 15 and 16 you are using two "int"s to create a double and loosing the decimal portion of the number just to store ".0000..." in the variable. If you change the numbers to "e = 2.0 / 5.0;" and the same for the next line you should see a difference.

What you have with your program works, but you could just as easily have initialized the variables when they are defined and eliminate lines 11 - 20.

1
2
3
4
int a{ 200 }, b{ -100 };
float c{ 15.123 }, d, e{ 2.0 / 5.0 }, f;
char letter{ 'T' }, letter1;
string word, word1{ "\"true\"" };

Just to give you an idea.

Hope that helps,

Andy
Hi Andy,

Thank you for your help and the info you gave me i really appreciate it.
The program works fine now.
Hello kakoda,

You are welcome. Anything that you do not understand let me know.

Andy
Topic archived. No new replies allowed.