Initializing a variable

Started by
4 comments, last by jellyfishchris 11 years, 2 months ago

I'm trying to make a program that takes three scores from the user then averages them, I think I almost have it down except that Im getting an error about not initializing one of my variables but I don't know where the problem lies.


 //Game Score Average
//Program that gets three game scores from user and displays the average

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
	int score1, score2, score3;
	int score4 = score1 + score2 + score3;

	//First score input
	cout << "Enter a number:";
	cin >> score1;

	//Second score input
	cout << "Enter a second number:";
	cin >> score2;
	
	//Third Score input
	cout << "Enter a third number:";
	cin >> score3;

	//Three scores averaged
	cout <<  score4;
	cout << "\n";

	system ("pause");
	return 0;
}

Advertisement
When you add score1, score2 and score3 together you haven't actually given them values yet. You need to add them after you get the input.

Thanks, I wasn't thinking about it linear so I didn't see the problem in the begining.

You need to add them after you get the input.

The code, int score4 = score1 + score2 + score3;, isn't read as "at any time, score4 is the sum of score1 and score2 and score3"; it is read as "store the sum of score1 and score2 and score3 into score4". Since score1 .. score3 haven't been assigned a value at the time, a compiler warning is issued. (On a side note, you'll need to divide by three to get the average.)

Thanks for the info, now I have to average but without a decimal vaule, I thought using double instead of int here


double score4 = (score1 + score2 + score3)/ 3;

would make it send out an average with decimals but it hasn't.

Your doing an int / int division this returns a int results and then your passing it to a double so...

5 / 2 = 2.5

2.5 - Convert to an int 2.

Convert 2 to a double 2.0

So an easy fix would be to do....


double score4 = (score1 + score2 + score3)/ 3.0;
 

This topic is closed to new replies.

Advertisement