Initializing a variable

This topic is 1803 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

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;
}


Share on other sites
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.

Share on other sites

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

Share on other sites

You need to add them after you get the input.

The code, [tt]int score4 = score1 + score2 + score3;[/tt], 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 [tt]score1[/tt] .. [tt]score3[/tt] 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.)

Share on other sites

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.

Share on other sites

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;