Why isn't the variables arithmetic working? - c++

Here is code:
#include<iostream>
#include<string>
using std::cout;
using std::cin;
using std::endl;
using std::string;
int score_one;
int score_two;
int score_third;
int final_score = score_one * score_two * score_third;
int main()
{
cout << "What was your first score?" << endl;
cin >> score_one;
cout << "What was your second score?" << endl;
cin >> score_two;
cout << "What was your third score?" << endl;
cin >> score_third;
cout << "Your average score is: " << final_score << endl;
return 0;
}
Originally I am trying to get the average, by dividing the three scores, but that doesn't work, nor my arithmetic. It does not even multiple the variables. I use cin to get the numbers. Not sure what I am missing.

At the time that you assign to final_score, the values of the other scores are 0 (as you haven't assigned to them yet and they're global). You then read into the scores, but never update final_score!
You need to add this after you read in the third score:
final_score = score_one * score_two * score_third;
This will update final_score.
I would also suggest staying away from global variables. I'd also suggest initializing your variables when you declare them to avoid garbage values.
Also, you're not actually calculating the average! To do that, you'll need to add your values and divide by 3, since you have 3 values total. But you've declared final_score as an integer, so you won't be able to store the average with full precision. I'd suggest declaring as a double.
Taking into account all these changes, your code will look like:
int main()
{
int score_one = 0;
int score_two = 0;
int score_third = 0;
double final_score = 0;
cout << "What was your first score?" << endl;
cin >> score_one;
cout << "What was your second score?" << endl;
cin >> score_two;
cout << "What was your third score?" << endl;
cin >> score_third;
final_score = (score_one + score_two + score_third) / static_cast<double>(3);
cout << "Your average score is: " << final_score << endl;
return 0;
}

This line should be moved after you cin to the variables on the right hand side of the equation
int final_score = score_one * score_two * score_third;
cout << "Your average score is: " << final_score << endl;
The variable isn't somehow recomputed when those variables are later set.

This part
int final_score = score_one * score_two * score_third;
should be inside main() after the last cin.

You have already received some answers, but I would like to offer another point of view.
It seems to me that you are used to a program like Excel, where you can set a cell to a formula (like the product of 3 other cells), and then, whenever you change any of those cells, the product is immediately updated, automatically. C++ (and, in general, programming languages) does not work like that. When you write a line like
int final_score = score_one * score_two * score_third;
you are not setting a rule, which will cause the value to be recalculated. The approach is different!
A program is executed from the beginning to the end (in practice, from the top to the bottom), and every time you assign a value to a variable (like final_score), what you are doing is reading the current value of the input variables (here, your three scores), calculating the result (which in this case is undefined, because you haven't initialised any of the scores), and assigning it to the variable, just this time. That's it. If you later change the scores, the change will not be reflected automatically on your final_score. If you want the value to be recalculated, you have to do it manually. That's why you have to move that line after the lines that read the input from the user, as the others have said.

You really should not use global variables, see here on why you should avoid them.
Next, instead of doing using std::cin etc. Just get used to typing it.
Lastly, use appropriate flags in your compiler to help you catch mistakes. The compiler is meant to be your friend. A good compiler would tell you,
int score_one;
int score_two;
int score_third;
int final_score = score_one + score_two + score+third / 3;
Is not initialized. To really achieve what you are thinking, you could use a function that will return a double. And that would look something like
double doAverage(int score1, int score2, int score3)
{
return (score1 + score2 + score3) / 3.0;
}
But that will probably come later in your coding practices.
#include<iostream>
int main()
{
// Delare your variables here and initialize them to zero.
int score_one = 0;
int score_two = 0;
int score_third = 0;
double final_score = 0;
std::cout << "What was your first score?" << std::endl;
std::cin >> score_one;
std::cout << "What was your second score?" << std::endl;
std::cin >> score_two;
std::cout << "What was your third score?" << std::endl;
std::cin >> score_third;
// Take all scores and divide it. This is the important part since
// order matters in your code.
final_score = (score_one + score_two + score_third) / 3.0;
std::cout << "Your average score is: " << final_score << std::endl;
return 0;
}
You're on the right track, you just have to look at your code and read it outloud to yourself. One of the best things you can do in programming is starting from the top and saying, "Okay, where does this break?" And follow it line by line making sense of it.

Related

What is the difference between "sum = addTwoNumbers" to just calling "addTwoNumbers"?

I'm a freshman in IT and we're currently discussing functions in C++. I just want to ask the difference between our prof's code and the other code that I tried.
This is the sample code our prof showed us:
#include<iostream> //header file
using namespace std;
int num1, num2, sum = 0; // global variable
int addTwoNumbers(int a, int b)
{
sum = a + b;
return sum;
}
int main()
{
cout << "Enter first number: ";
cin >> num1;
cout << "Enter second number: ";
cin >> num2;
sum = addTwoNumbers(num1, num2);
cout << "\nThe sum is " << sum;
}
and as for the code I tried, I simply removed the "sum =" part. So,
addTwoNumbers (num1, num2);
cout << "\nThe sum is " << sum;
and it still did the same thing. At least, from what I saw in the output. Is there any difference between the two behind the scenes or is there really nothing?
The 1st code is ... confusing. I hope your professor didn't show this code to introduce you to functions, but to rather quiz your already knowledge of functions and global variables.
The confusing part are the global variables and how they are used inside the function. If we remove them and forget about them completely the code is better suited to teach you about functions. Let's see:
#include <iostream>
int addTwoNumbers(int a, int b)
{
int sum = a + b;
return sum;
// or simply:
// return a + b;
}
int main()
{
int num1, num2;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
int sum = addTwoNumbers(num1, num2);
std::cout << "\nThe sum is " << sum;
}
Now there are no hidden dependencies between main and addTwoNumbers (in the form of the global variables). This illustrates the procedure of passing data to function and getting data back from the function (parameters and return). Analyze this code and understand how it works. Play with it.
Now this won't work:
addTwoNumbers (num1, num2);
cout << "\nThe sum is " << sum;
Because the only way data escapes the function is via its return. Since you discard the return value (you don't assign the result of calling the function) you don't have the result of the sum.
Now you could say you could do this instead:
int sum = num1 + num2;
cout << "\nThe sum is " << sum;
and ask "what's the point of functions?"
True for this particular small function there is no practical point of having it. You'll always write the num1 + num2 instead. However its simplicity makes it perfect as a teaching tool. You will soon see functions that get more complex and you will learn (either by being told or learning yourself the hard way) that writing code in very small chinks (functions) is better for both writing (breaking down the big problem in smaller problems) as well as for reading.
First of all, the reason why the sum is returning those values is that you are assigning the sum to itself. Basically, the addTwoNumber() returns the sum, and then you are assigning that value back into the sum. Hence, you don't need to assign the sum again in other words (sum = addTwoNumbers is unnecessary).
Yes, your code is working and it is actually better than the teachers in this case. However, your teacher may want to show you that you can use global variables like this. Typically you would store that value in another variable for later use if needed.

Is there a way to shorten this project?

I wrote a project that calculates the area of the triangle.
I have wrote this program.
#include <iostream>
using namespace std;
int main()
{
int first, two, three;
int all = (first + two) * three;
cout << "Enter first num: ";
cin >> first;
cout << "\nEnter second num: ";
cin >> two;
cout << "\nEnter num three: ";
cin >> three;
cout << "You have choosed to do: (" << first << " + " << two << ") * " << three;
cout << "\n\nThis is equal to: " << all;
return 0;
}
Instead of going down a line and writing cin and cout every time, is there a way to shorten this project and make it shorter.
Maybe like write the cout and the cin in a single line ?
or anything else just to make it look more clean and nice.
it looked messy.
Thanks!
This takes a whole 1 line fewer. Whether it's cleaner or easier to understand is up to you ....
int sides[3];
for (int i=0; i < 3; i++)
{
cout << "Enter side " << i+1 << endl;
cin >> sides[i];
}
It's good to write short code where it makes it clearer, so do keep considering how you can do that. Making it look pretty is a worthy consideration too - again as long as it makes what you're doing clearer.
Clarity is everything!!
If you really want to shorten your project and make it more "clean" you can do it this way.
#include <iostream>
int main()
{
std::string str = "string"; std::cin >> str;
return 0;
}
Like you wanted to write cout and cin in a single line, you could write like that, but I think it's not "clean" to write that way and it's better to drop a line.
And, please don't use using namespace std; its a bad practice.
To make the code more maintainable and readable:
1) Use more meaningful variable names, or if you would name them consecutively, use an array
e.g. int numbers[3]
2) Similarly, when you are taking prompts like this, consider having the prompts in a parallel array for the questions, or if they are the same prompt use something similar to noelicus answer.
I would do something like this:
int numbers[3];
String prompts[3] = {"put your", "prompts", "here"};
for(int i=0; i<3; i++){
cout << prompts[i] << endl;
cin >> numbers[i]
}
//do math
//print output
also, you may want to check to make sure the user has entered a number using this.

Getting strange value

I'm currently learning about functions in C++ and am currently working on a homework assignment with functions being the main thing.
Currently, I'm trying to make a grade calculator with every operation of the process being split into a function of its own.
Here's the code:
#include <iostream>
#include <fstream>
#include <string>
#include <stdlib.h>
using namespace std;
void getHWGrades(int homeworks[], int size)
{
cout << "\nEnter the grades, out of 100 points, for the 9 homeworks you completed." << endl;
cout << "Note that Homework 10 is given to you for free, but is the same grade \nas homework 9.\n" << endl;
for (int i = 0; i < 9; i++)
{
cout << "Homework " << i + 1 << ": ";
cin >> homeworks[i];
while (homeworks[i] > 100 || homeworks[i] < 0)
{
cout << "Invalid grade, input homework grade again: ";
cin >> homeworks[i];
}
}
homeworks[9] = homeworks[8];
cout << "Homework 10: " << homeworks[9];
}
double quizAverage()
{
double quizPts;
cout << "Input your in class quiz average: ";
cin >> quizPts;
return quizPts;
}
double labAverage()
{
double labPts;
cout << "Input your lab average: ";
cin >> labPts;
return labPts;
}
double teamProject()
{
double teamPts;
cout << "Input your team project grade: ";
cin >> teamPts;
return teamPts;
}
int exam1()
{
int exam1Pts;
cout << "Input your exam1 grade: ";
cin >> exam1Pts;
return exam1Pts;
}
int exam2()
{
int exam2Pts;
cout << "Input your exam2 grade: ";
cin >> exam2Pts;
return exam2Pts;
}
double hwAverage(int homeworks[], int size)
{
double total = 0;
double homeworkAverage = 0;
for (int i = 0; i < size; i++)
{
total = total + homeworks[i];
}
homeworkAverage = (total*1.0) / 10;
return homeworkAverage;
}
double currentPoints(double& quizPts, double& labPts, double& teamPts, double& homeworkAverage, int& exam1Pts, int& exam2Pts)
{
double totalPts = ((quizPts / 100.0) * 10) + ((labPts / 100.0) * 10) + ((teamPts / 100.0) * 15) + ((homeworkAverage / 100.0) * 20) + ((exam1Pts / 100.0) * 10) + ((exam2Pts / 100.0) * 15);
cout << "\nYour current points (out of the 80 total available), stand at: " << totalPts;
return totalPts;
}
double currentAverage(double& totalPts)
{
double availableAverage = totalPts*(100.0 / 80);
cout << "\nYour current average is: " << availableAverage;
return availableAverage;
}
int main()
{
// keep the console from closing in visual studio
char charer;
double totalPts;
double quizPts, labPts, teamPts, homeworkAverage;
int exam1Pts, exam2Pts;
const int ARRAY_SIZE = 10;
int hwArray[ARRAY_SIZE];
getHWGrades(hwArray, ARRAY_SIZE);
quizAverage();
labAverage();
teamProject();
exam1();
exam2();
currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
cin >> charer;
}
My issue, which I believe lies in the functions currentPoints and currentAverage, is that when I run this totalPts outputs as -5.09078e+61 and as a follow up result with the currentAverage function, availableAverage outputs as -1.157e+62.
I'm sure that the issue has to do with how I'm passing the values from function to function (which I doubt I'm doing correctly).
How would I go about fixing this issue?
Thank you in advance.
You need to store the return value from currentPoints() function, like this.
totalPts = currentPoints(quizPts, labPts, teamPts, homeworkAverage, exam1Pts, exam2Pts);
currentAverage(totalPts);
Reason is, you declared "totalPts" as local variable in currentPoints().
"Local variables has function scope only, it is undefined to main function".
Do this for all other
functions(quizAverage,labAverage,teamProject,exam1,exam2, hwAverage,currentAverage)
I hope, this will solve the issue !!!
The problem is not about functions, it's about variables.
Let's take quizPts for instance:
In the main method, you declare this variable, but then you don't do anything with it before sending it to currentPoints. Therefore it has an undefined value when you do so (undefined often looks like random in C).
The other variable quizPts you use in quizAverage have the same name but is not the same for the compiler.
Try in your main:
quizPts = quizAverage();
You asked
How would I go about fixing this issue?
And the answer is "Use the debugging tool with "watches" window open in your favorite IDE".
It's always very difficult to find an error simply by re-reading the code, but in the debugger you can see all the values of your variables at each moment of time. Specifically, in this example, you would realize that your variables have garbage values from the very beginning (are not initialized), and this value never changes.
Using this approach you could find the reason yourself in time less than necessary to write this SO question. I hope this will help you to save your time in future.
The problem is you use the variables such as quizPts and labPts without storing any value in them. In your case, you have to store the return value of the function to the corresponding variable before using it. For example, do the same as the following statement:
quizPts = quizAverage();

uninitialized?, tuitionCost, local Variable, [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
int main()
{
double tuitionCalc(int sumCreditHoursTaken);
int numCourses;
double total = 0.0;
double tuitionCost= 0.0;
cout << "\t\t This Program calculates a student's total number of\n";
cout << "\t\tcredit hours and tution for a given semester.\n";
cout << "\nPlease enter the number of Courses you will be taking this semester: ";
cin >> numCourses;
for ( int count = 1; count <= numCourses; count++)
{
double sumCreditHoursTaken;
cout << " please enter the number of credit hours for course" << count << ": ";
cin >> sumCreditHoursTaken;
total += sumCreditHoursTaken;
}
cout << fixed << showpoint << setprecision(2);
cout << "Your Total number of credit hours is: " << total << endl;
cout << "Your total tuition will be: $" << tuitionCalc(tuitionCost) << "\n\n";
return 0;
}
and the function im calling is
double tuitionCalc(int sumCreditHoursTaken)
{
double tuitionCost = 0.0;
double costCreditHour = 147.00;
double maxHoursFullTuition = 12;
double maintFeeAddOn = 29.33;`
if (sumCreditHoursTaken <= maxHoursFullTuition)
cout<< " " << (sumCreditHoursTaken * costCreditHour);
else if (sumCreditHoursTaken > maxHoursFullTuition)
cout << " " << (maxHoursFullTuition * costCreditHour) + ((sumCreditHoursTaken - maxHoursFullTuition) * maintFeeAddOn);
return tuitionCost;
}
input for number of courses is 5
and credit hours is 3,3,3.5,4,2.5
i get the total credit hours but icant seem to display the tuition cost?
thank you s
You are never actually assigning a value to tuitionCost in tuitionCalc() method, so it will always be 0.0.
To elaborate: You are returning tuitionCost from tuitionCalc(). You first initialize tuitionCost = 0.0, but never proceed to assign any calculated value to it. Thus, when you return tuitionCost, it will return the value you initialized it to: 0.0.
I haven't examined your code in detail, but if you inputs contain floating point numbers then change the type for sumCreditHoursTaken from int to double.
Also, change the parameter for the invocation of tuitionCalc from tuitionCost to total.
It seems that OP has fallen afoul of misunderstanding scope and how variables are passed to functions.
In main, OP defines tuitionCost. tuitionCalc defines another tuitionCost. These are different tuitionCosts. They represent different locations in memory and can store different values.
Next, because the tuitionCalc function is defined
double tuitionCalc(int sumCreditHoursTaken)
tuitionCalc(tuitionCost) will take tuitionCost convert it to an integer, and pass a copy into tuitionCalc where it will be used with the name sumCreditHoursTaken. One could say OP has three tuitionCalcs at this point. Not what they want.
Breaking down the tuitionCalc prototype, we see that it takes sumCreditHoursTaken, an integer and based on the name the number of credit hours taken, not a total cost. tuitionCalc also returns a double and inferring the purpose of the function from it;'s name, one would expect that it calculates and returns the tuition.
Like Anatoly states in his answer, the input to tuitionCalc should almost certainly be total, the total number of credit hours computed, and the output should be tuitionCost.
Since this has the smell of a homework assignment, it's not in the OP's best interests to fully answer the question. Instead here are a few recommendations:
Eliminate tuitionCost from main. It only serves to increase confusion. You can reuse variable names, but only do it where there is a clear benefit. If you have a cost and a function that takes and uses cost, then using cost for both makes sense. Just remember that cost inside the function is a different entity unless you pass by reference. In
void function(int & cost)
called with
function(cost);
both costs are the same. But in
void function(int cost)
called with
function(cost);
both function's cost is a copy of the caller's cost and any changes made by function will only effect the copy.
Declare variables close to where you use them. This way people reading your code don't have to scroll up and down and otherwise go hunting. It also helps you because it makes mistakes like, "Why am a calling a function that takes an int with a double?" more obvious.
Do not cout in tuitionCalc. Compute and return tuitionCost. Allow main to output tuitionCost. A function with a name like calc should only calculate. Names should describe function as closely as possible.
First of all you should create the function prototype before declaring it.
And there were some confusions in the code you have used I tried my best to omit error hope this is helpful!
#include <iostream>
#include <iomanip>
using namespace std;
double tuitionCal(double sumCreditHoursTaken);
int main() {
double tuitionCalc(int sumCreditHoursTaken);
int numCourses;
double total = 0.0;
//double tuitionCost= 0.0;
cout << "\t\t This Program calculates a student's total number of\n";
cout << "\t\tcredit hours and tution for a given semester.\n";
cout << "\nPlease enter the number of Courses you will be taking this semester: ";
cin >> numCourses;
double sumCreditHoursTaken; // you should create this variable outside the for loop
for ( int count = 1; count <= numCourses; count++)
{
cout << " please enter the number of credit hours for course" << count << ": ";
cin >> sumCreditHoursTaken;
total += sumCreditHoursTaken;
}
double tuitionCost=tuitionCal(total);
cout << fixed << showpoint << setprecision(2);
cout << "Your Total number of credit hours is: " << total << endl;
cout << "Your total tuition will be: $" <<tuitionCost<< "\n\n";// I assume this is what you want
return 0;
}
double tuitionCal(double sumCreditHoursTaken)//the parameter type is double now
{
double tuitionCost = 0.0;
double costCreditHour = 147.00;
double maxHoursFullTuition = 12;
double maintFeeAddOn = 29.33;
if (sumCreditHoursTaken <= maxHoursFullTuition)
tuitionCost=(sumCreditHoursTaken * costCreditHour);
else if (sumCreditHoursTaken > maxHoursFullTuition)
tuitionCost=(maxHoursFullTuition * costCreditHour) + ((sumCreditHoursTaken - maxHoursFullTuition) * maintFeeAddOn);
return tuitionCost;
//I don't see a point of returning the value and couting both you can
//do only one of the oprations
}

Gross Pay using Arrays (C++)

I am writing a code to calculate the gross pay of seven employees using arrays. Here is what I have so far
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
//Set all constants and variables
const int SIZE = 7; //Size of all arrays
int emID[SIZE] = {1234, 4563, 8765, 4568, 9867, 9235, 7684};
double Hours[SIZE],
Rate[SIZE],
Gross[SIZE];
int index;
Gross[index] = (Hours[index] * Rate[index]);
//Explain Program
cout << "This program calculates an employees gross pay\n";
for (Hours[index];index <= 6; index++)
{
cout << "How many hours did employee " << emID[index] << " work?\n";
cin >> Hours[index];
}
for (Rate[index]; index <= 6; index++)
{
cout << "Enter the pay rate for " << emID[index] << endl;
cin >> Rate[index];
}
for (Gross[index]; index <=6 ; index++)
{
cout << "The gross pay for " << emID[index] << " is " << Hours[index] * Rate[index];
}
}
Unfortunately the program terminates after the first "for" loop. Any suggestions?
There seem to be a few mistakes in your code, which I'm pointing out below.
index is unitialised, and the way you've used it results in Undefined Behavior. I think you meant to initialise to to 0.
You should reset the value of index to 0 between for loops. Currently you would iterate in the first for loop. After that, since index will be > 6, your code will not execute the other two for loops.
Your first term in the for loop declarations is wrong. I think you meant to declare index = 0 there. If not, you should leave it empty.
The line near the beginning where you calculate Gross[index] is wrong and redundant.