So the below code works fine, with one exception:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
int value1, value2, value3, value4;
float calcMean,calcStDev;
// Input values from keyboard
// prompt user for input
cout << "Enter 1st value. " << endl;
cin >> value1;
cout << "Enter 2nd value. " << endl;
cin >> value2;
cout << "Enter 3rd value. " << endl;
cin >> value3;
cout << "Enter 4th value. " << endl;
cin >> value4;
// Calculate the mean, mean = (value1 + value2 + value3 + value4)/4.0
calcMean = (value1 + value2 + value3 + value4) / 4.0;
// Calculate the standard deviation, standard deviation = squareroot((sum((input value-mean)*(input value-mean)))/number of input value - 1)
calcStDev = sqrt((pow((value1 - calcMean),2) + pow((value2 - calcMean),2) + pow((value3 - calcMean),2) + pow((value4 - calcMean),2))/(4-1));
// Output display
cout << fixed << setprecision(2) << endl;
cout << "Mean of the four values: " << setw(10) << calcMean << endl;
cout << "Standard deviation of the four values: " << setw(10) << calcStDev << endl;
cin.get();
cin.get();
return 0;
}
The output doesn't seem to be responding to the setw() like I expected (I wanted the number 18.50 to be directly over 19.64, one on top of the other).
Any idea what I am doing wrong?:
Enter 1st value.
2
Enter 2nd value.
36
Enter 3rd value.
35
Enter 4th value.
1
Mean of the four values: 18.50
Standard deviation of the four values: 19.64
I think that the problem is that string literal "Mean of the four values: " contains embedded tab characters. It is possible that to insert spaces you pressed the TAB key instead of SPACEBAR key.
Related
I'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.
Hello everyone this is my code and I just help I managed to correct the first 3 questions but the rest I am still getting errors.
Below is the all question :
Complete the provided main() program with statements to accomplish each of the following. In each case you must use the appropriate I/O stream manipulators to produce the appropriate output wherever possible.
Output first first as an integer value, followed by a space, then in
its written form.
Output second as a base ten value, followed by a space, then as a
hexadecimal
value, followed by a space, then as an octal value. Make sure the
appropriate base indicator prefix is shown in the output.
Output third.
Output fourth with four digits, with the sign shown at the left, and
the value right aligned. The decimal point must also appear.
Output fourth with four significant figures.
Output fifth with seven significant figures. (Note: use left alignment here)
Output fifth with three digits to the right of the decimal point.
Output third.
Output fourth with two digits to the right of the decimal point.
Output sixth with no decimal portion showing
Output fourth with eight digits to the right of the decimal point.
Output sixth with six digits.
Here is my code so far :
#include <iostream>
#include <iomanip>
using namespace std;
int
main0()
{
bool first;
int second;
long third;
float fourth;
float fifth;
double sixth;
cout << "Enter bool, int, long, float, float, and double values: ";
cin >> first >> second >> third >> fourth >> fifth >> sixth;
cout << endl;
cout << noboolalpha << first;
cout << " ";
cout << boolalpha << first << endl;
cout <<left << dec << showbase;
cout << second;
cout << " ";
cout << internal << hex << showbase;
cout << second;
cout << " ";
cout <<right << oct <<showbase;
cout << second << endl;
cout << third<< scientific<< endl;
cout <<left << setw(4)<<fixed<< fourth <<endl;
cout <<setprecision(4)<< fourth <<endl;
cout <<left<<setw(7)<< fifth << endl;
cout <<right<<setprecision(3)<< fifth;
cout <<third<<endl;
cout <<right<<setw(2)<<fourth<<endl;
cout << fixed<<sixth<< endl;
cout << right << fixed<<setprecision(8)<< fourth<< endl;
cout <<left<<showpoint <<setprecision(6)<<sixth;
// ***** Solution ends here ****
cin.get();
return 0;
}
I answered 4-6:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
long third = 123654123654123LL;
float fourth = 12335.67890;
std::ios initialState(nullptr);
initialState.copyfmt(std::cout);
// 4
cout << third << scientific<< endl;
// 5
cout << showpoint << fixed << setprecision(4) << right << showpos << fourth << endl;
cout.copyfmt(initialState);
// 6
cout << setprecision(4) << fourth << endl;
return 0;
}
Good luck with the rest.
My program runs the first For loop correctly then skips the Cin's on the 2nd and 3rd cycle. Then when the loop is finished it goes on to calculate the BMI of the first index [0] and does this correctly and gives the right answer but then nothing for the index's 1 and [2] because no information was inputted because the cin's were skipped.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
struct Patient
{
double height;
double weight;
int age;
bool isMale;
};
int main()
{
Patient Patients[3];
for (int i = 0; i < 3; i++) {
cout << "Patient "<< i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << endl << endl;
}
cout << endl << endl;
for (int i = 0; i < 3; i++) {
float BMI = Patients[i].weight / (Patients[i].height *Patients[i].height);
cout << "Patient " << i << " Has A BMI of: " << BMI << endl << endl;
}
return 0;
}
This is the console where you can see after the first loop all the cin's are skipped but the first loop was correctly stored as it couted the BMI of the first index:
You see that you are having an error at the end of the loop. You can see from iterations 2 and 3 that cin is not behaving the same way each time. There are a couple of error state flags that come from ios that will help you see what's going wrong here. See iso::good for details. If you add those checks:
for (int i = 0; i < 3; i++) {
cout << "Patient " << i << " Height: ";
cin >> Patients[i].height;
cout << "Patient " << i << " Weight: ";
cin >> Patients[i].weight;
cout << "Patient " << i << " Age: ";
cin >> Patients[i].age;
cout << "Is Patient " << i << " Male True or False: ";
cin >> Patients[i].isMale;
cout << cin.good() << '\n';
cout << cin.eof() << '\n';
cout << cin.fail() << '\n';
cout << cin.bad() << '\n';
cout << endl << endl;
}
What you will see if that cin is no longer good, it is not eof it is fail, and it is not bad. While the fail bit is set, cin will not work. Hence you see the result. Looking at the chart in the link you see this:
Logical error on i/o operation
You were preforming an i/o operation of inserting "true" into a bool. The word true is probably stored as a character array or string, not a boolean. How should cin convert this to a boolean? You need to trap your input and convert it into a bool or switch to use an input that can be explicitly converted into a bool.
For example:
cout << "Is Patient " << i << " Male? (1 for Male, 0 for Female):";
cin >> Patients[i].isMale;
In this case the cin recognizes 1 and 0 as integers and can convert an integer into a boolean. 0 is false, everything else is true. Another option is to let the library do it and use boolalpha. You can read about it here.
This shows a larger issue. What happens if I write "two point five" as the answer to height? In this case we can assume some intelligence on the part of the user, but thinking about things like this will help write more robust code in the future.
You can fix your program in two ways.
Just input "0" or "1" in the male/female question instead of "true" or "false".
Change this line and continue to input "true" or "false":
cin >> boolalpha >> Patients[i].isMale;
Sources:
Cin and Boolean input
http://www.cplusplus.com/reference/ios/boolalpha/
just started reading a C++ book and one of the practice problems was to write a small calculator that takes as input one of the four arithmetic operations, the two arguments to those operations, and then prints out the results.
Sadly, the program works up until the user inputs the arithmetic option.
So if I chose to do multiplication, id write "Multiplication" and it was just stay there and not do anything after.
Image of the problem im having
#include <iostream>
#include <string>
using namespace std;
int main(){
// Simple calculator program
// Declaring three variables
float numberOne;
float numberTwo;
string operationOption;
// Asking the user which two numbers he/she will use
cout << "Enter the first number you would like to apply a arithmetic operation to: ";
cin >> numberOne;
cin.ignore();
cout << "Now enter the second number: ";
cin >> numberTwo;
cin.ignore();
// Using cin to input users selection
cout << "Enter the operation you want to perform." << endl;
cout << "The options you have are: " << endl;
cout << "Multiplication, Subraction, Division and Addition: " << endl;
cin >> operationOption;
cin.ignore();
cin.get();
// Where it all happens
if ( operationOption == "Multiplication" ) {
cout << "The first number multiplied by the second number is: " << numberOne * numberTwo << endl;
} else if ( operationOption == "Division" ) {
cout << "The first number divided by the second number is: " << numberOne / numberTwo << endl;
} else if ( operationOption == "Subtraction" ) {
cout << "The first number subtracted by the second number is: " << numberOne - numberTwo << endl;
} else if ( operationOption == "Addition ") {
cout << "The first number added to the second number is: " << numberOne + numberTwo << endl;
} else {
cout << "You entered an invalid option.";
};
}
Remove line :
cin.get();
will solve your problem
I need help with a program for school. We had to write a program that asks the user for information about a baseball player. We need to calculate the players batting average with their games played, number of times at bat and number of hits. I am running into an issue where my computation for the average is outputting a set number and not performing any computations. I am entering whole integers for all the variables that are used for calculation. So i would input numbers like 1, 4 , 10 etc... As the program stands the value my formula is setting itself equal to is 15903.876. All of my variables used for the average formula are declared as integers and the batting average itself is declared as a double. I have done some debugging my self and found that the computation messes up when it divides the number of times at bat by the number of hits. If anyone could help me figure out the issue i would appreciate it.
//libaries
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
class battingAverage
{
public:
string pName;
int nBats;
int tHits;
int gPlayed;
int gcalled;
double average;
double average1;
double playeraverage;
};
int main()
{
string numberPlayers;
int nplayers;
//enters the number of players the user wants to enter data for
cout << "Enter the number of players you want to enter data for: ";
cin >> numberPlayers;
cout << endl;
//converts the value of numberPlayers to nplayers
istringstream convert(numberPlayers);
//sets integer nplayers equal to the value of the string numberPlayers
if(! (istringstream(numberPlayers) >> nplayers) )
{
nplayers = 0;
}
cout << "This program calculates the batting average of baseball players.\nYou may enter data for " << nplayers << " players." << endl;
battingAverage ba[nplayers];
int index = 0;
//while statement to get data
while(index < nplayers)
{
cout << "Enter the players last name: " << endl;
cin >> ba[index].pName;
cout << "Enter the number of games the player played: " << endl;
cin >> ba[index].gPlayed;
cout << ba[index].gPlayed << endl;
cout << "Enter the number of games the player was called in for: " << endl;
cin >> ba[index].gcalled;
cout << ba[index].gcalled << endl;
cout << "Enter the number of times the player was at bat: " << endl;
cin >> ba[index].nBats;
cout << ba[index].nBats << endl;
cout << "Enter the number of time the player hit: " << endl;
cin >> ba[index].tHits;
cout << ba[index].tHits << endl;
if(ba[index].tHits > ba[index].nBats)
{
cout << "Enter a valid value for the number of times the player hit: ";
cin >> ba[index].tHits;
}
cout << endl;
index++;
}
//rounds average to 3 decimal places
cout << fixed << setprecision( 3 );
//average formula
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
cout << ba[index].playeraverage << endl << endl;//just temp line to check calculation of average.
ba[index].average = .000;
ba[index].average1 = .099;
while(ba[index].average < 1 && ba[index].average1 < .899)
{
ba[index].average +=.100;
ba[index].average1 += .1;
//prints chart
cout << setprecision( 1 ) << ba[index].average << "00" << setprecision( 3 ) << setw(12) << ba[index].average1 << endl;
}
cout << "1.000" << setw(12) << "1.000" << endl;
//version of system pause
cout << "\nPress enter to continue...";
cin.sync();
cin.ignore();
return 0;
}
On this line:
ba[index].playeraverage = (ba[index].nBats / ba[index].tHits) * (ba[index].gPlayed / ba[index].gcalled);//error
You have this expression:
(ba[index].nBats / ba[index].tHits)
Because both nBats and tHits are integers, you're using only integer math.
The answer will be an integer.
For example:
nBats = 10 & tHits = 3, you'd expect the expression to be 3.333.
But it would only be 3
To fix this, I recommend changing to:
((double)ba[index].nBats / ba[index].tHits)
Same thing again with the expression about gPlayed and gcalled.
Your value of index is wrong during the calculations.
I found this as soon as I put your code in a debugger and stepped through it, something you really should have done yourself.
You start with int index = 0;, and increment it as the user puts in each player's data.
At the end of the input-loop, index is now the same as the number of players.
(eg. if you had 5 players, index is now 5, and the player data is stored in ba[0], ba[1], ba[2], ba[3], and ba[4])
Note that at this point ba[5] is NOT valid data. But that is exactly where ba[index] is!
You do all your calculations on ba[index], which is invalid data, and you wonder why you get meaningless results?
I recommend you set index back to 0 before starting your calculations, and make another loop that does the necessary calculations for each player 0...4.