Skip to main content
GameDev.net gamedev.net
🔒 Locked

Initializing a variable

Started by ???????p??u??bn? Feb 12, 2013 at 11:38 PM 4 replies 2.2k views
Original Post
???????p??u??bn?
???????p??u??bn?

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;
}
SiCrane
SiCrane
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.
???????p??u??bn?
???????p??u??bn?

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

fastcall22
fastcall22

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.)
???????p??u??bn?
???????p??u??bn?

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.

jellyfishchris
jellyfishchris

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;
 

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.