Small problem with printing float array elements.

Doing a school assignment where I have to read weight and put them in an array. Our teacher insists we use float as the data type as weight can sometimes be in decimals, too.
Why am I getting:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Enter the name: asd

Enter the weight: 23

Enter the name: de

Enter the weight: 45

Enter the name: as

Enter the weight: 55

Name: asd
Weight: 2.8026e-45

Name: de
Weight: 0

Name: as
Weight: 5.88323e-39

These numbers as output when I want to output the exact number read by the compiler?


Here's the 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
25
26
27
  #include<iostream>
using namespace std;
int main()
{
	float weight[4], f_weight=0.0;
	string name[4], s_name;
	for(int i=0;i<3;i++)
	{
		cout<< endl << "Enter the name: ";
		cin>>s_name;
		name[i]=s_name;
		cout<< endl << "Enter the weight: ";
		cin>>f_weight;
		if(f_weight < 15 or f_weight > 150)
		{
			cout<< "Invalid input. Please enter weight again: ";
			cin>>f_weight;
		}
		
	}
	for(int k=0;k<3;k++)
	{
		cout<< endl << "Name: " << name[k] << endl;
		cout<< "Weight: " << weight[k] << endl;
	}
	system("PAUSE");
}
Last edited on
You may want to look at std::fixed and std::setprecision (iomanip). These let you print floating point and double precision numbers in a more easy to read format.
if(f_weight < 15 or f_weight > 150)

the "or" doesnt work that way. If you want to say "or" you do it using these ||

if(f_weight < 15 || f_weight > 150)
@Texan40

Isn't there a simpler way to do it or should I refrain from using float completely?

@TarikNeaj

The pipe? I've been using it but I find using 'or' better, I don't think there's any difference between the two at all, both work the same way.
Here is how I would have written the program -

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
        float weight[3];
	string name[3];

		for (int i = 0; i<3; i++)
		{
			cout << "Enter the name: ";
			cin >> name[i];

			cout << endl << "Enter the weight: ";
			cin >> weight[i];
			cout << endl;

			if (weight[i] < 15 || weight[i] > 150)
			{
				cout << "Invalid input. Please enter weight again: ";
				cin >> weight[i];
			}


		}
		
		for (int k = 0; k < 3; k++)
		{
			cout << endl << "Name: " << name[k] << endl;
			cout << "Weight: " << weight[k] << endl;
		}


Here is how I would have written the program. Compare it to yours, try and understand what Ive done.
The last time I used the array element in a selection the compiler gave an error, I must've been using it wrong. It still doesn't solve the main problem, though.
Last edited on
Could you post the code again with some of the changes you've made?
Nevermind, I'm an idiot. It's fixed. I'm not sure why removing the separate variables from the code fixed it.
Topic archived. No new replies allowed.