This is my code. The information my professor gave us to only show 2 decimal points is out.precision(2) ;.
cout << "Welcome to the Book Store" << endl << endl;
cout << "Enter the single copy price: $" ;
cin >> single_copy_price ;
cout << "Enter the number of books sold: " ;
cin >> num_of_books_sold ;
cout << "Enter the discount percentage: " ;
cin >> discount_percentage ;
cout << "********************************************" << endl ;
subtotal = single_copy_price * num_of_books_sold ;
cout.precision(2) ;
cout<< "Subtotal: $" << subtotal << endl ;
cout << "Discount percentage: " << discount_percentage << "%" << endl ;
discount_ammount = subtotal * (discount_percentage / 100) ;
cout.precision(2) ;
cout << "Discount ammount: $ " << discount_ammount << endl ;
cout.precision(2) ;
cout << "Final price: $" << subtotal - discount_ammount << endl ;
return 0;
`
However, this is my result:
Welcome to the Book Store
Enter the single copy price: $10.50
Enter the number of books sold: 20
Enter the discount percentage: 15
Subtotal: $2.1e+02
Discount percentage: 15%
Discount ammount: $ 32
Final price: $1.8e+02
Program ended with exit code: 0
Thank you for the help!
The problem is the cout.setprecision(2). What it does is limit the number of significant figures in a number displayed. It's useful for scientific work, but not what you are looking for.
One person's solution was to write their own formatting method: http://www.arachnoid.com/cpptutor/student3.html
At the very end is point 6, for currency. His solution also formats with $ and commas for thousands places.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void showCurrency(double dv, int width = 14)
{
const string radix = ".";
const string thousands = ",";
const string unit = "$";
unsigned long v = (unsigned long) ((dv * 100.0) + .5);
string fmt,digit;
int i = -2;
do {
if(i == 0) {
fmt = radix + fmt;
}
if((i > 0) && (!(i % 3))) {
fmt = thousands + fmt;
}
digit = (v % 10) + '0';
fmt = digit + fmt;
v /= 10;
i++;
}
while((v) || (i < 1));
cout << unit << setw(width) << fmt.c_str() << endl;
}
The most simple solution is to set your precision to 2 more than the number of digits in the integer portion. To figure that out, cast to int and count the number of times you can divide by 10 with a non-zero result.
Related
I am making a C++ program to estimate your height based on your parents. I want to make it so I can output both the height in Feet and Inches. I don't know how to store the output from the cout in
if (boygirl == "boy") {
cout <<"Your estimated height is " << (mom *13/12 + dad) / 2 << " inches";
} and else if (boygirl == "girl") {
cout <<"Your estimated height is " << (dad+12/13 + mom) / 2 <<" inches";
into a variable so I can take the data from the variable and use it instead of asking for the results for inches in the previous step.
You might need to run the code to see what I mean.
If you don't understand what I mean, feel free to comment.
#include <iostream>
#include <string>
using namespace std;
void Convert(int inch) {
int feet, inches;
inches = inch % 12;
feet = inch / 12;
cout << "\n\t\tThe height in feet is " << feet << "\'" << inches << "\" " << endl;
}
int main() {
int i = 0;
do {
float mom;
float dad;
string doyouwish;
string boygirl;
cout << " \n\nWELCOME TO THE C++ HEIGHT PREDICTION PROGRAM";
cout << "\n\n INPUT GENDER TO BEGIN boy/girl: ";
cin >> boygirl;
cout << "How tall is your mother in inches: ";
cin >> mom;
cout << "How tall is your father in inches: ";
cin >> dad;
if (boygirl == "boy") {
cout << "Your estimated height is " << (mom * 13 / 12 + dad) / 2 << " inches";
} else if (boygirl == "girl") {
cout << "Your estimated height is " << (dad + 12 / 13 + mom) / 2 << " inches";
}
int htInches;
// Ask height from user
cout << "\n\ntEnter height in Inches from the previous results: ";
cin >> htInches;
Convert(htInches);
cout << "\n\n\n";
++i;
} while (i < 10);
}
Are you looking for something like this:
int htInches = 0;
if (boygirl == "boy") {
htInches = (mom * 13 / 12 + dad) / 2;
} else if (boygirl == "girl") {
htInches = (dad + 12 / 13 + mom) / 2;
}
cout << "Your estimated height is " << htInches << " inches";
Compute the result, store it in a variable, and then print it.
I'm fairly new to c++ and I am writing a program that calculates the balance of a savings account at the end of a three-month period. I am supposed to use loops, which I have done and don't have much of a problem. The problem I am having is that all the numbers for deposit, withdrawal, current balance, etc. are supposed to be displayed as x.xx, and I am getting that output, but it also does that for the month. How do I make it so that the month doesn't display as x.xx?
Here's my code:
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
double startbalance;
double annualrate;
double monthlyrate;
double deposit;
double withdrawal;
double totaldeposit = 0;
double totalwithdrawal = 0;
double totalinterest = 0;
double monthstart = 0;
double monthend = 0;
printf("Welcome to Your Bank!\n");
cout << "What is your starting Balance? $";
cin >> startbalance;
cout << "What is the annual interest rate?. Please enter whole value. For example 6 for 6% :";
cin >> annualrate;
monthend += startbalance;
for (double month = 1; month <= 3; month++)
{
cout << "Month #" << month << endl;
do
{
cout << setprecision(2) << fixed;
cout << "Current Balance: $" << monthend << endl;
cout << "Please enter total amount of deposits: $";
cin >> deposit;
if (deposit < 0)
{
cout << "Deposit must be a positive number!\n";
}
} while (deposit < 0);
totaldeposit += deposit;
monthend += deposit;
do
{
cout << "Please enter total amount of withdrawals: $";
cin >> withdrawal;
if (withdrawal < 0 || withdrawal > monthend)
{
cout << "Withdrawal must be a positive number and not be larger than balance: $" << monthend << endl;
}
} while (withdrawal < 0 || withdrawal > totaldeposit);
cout << endl;
totalwithdrawal += withdrawal;
monthend -= withdrawal;
monthlyrate = ((monthstart + monthend) / 2 * (annualrate / 12));
totalinterest += monthlyrate;
cout << "New Balance: $" << monthend << "\n";
}
cout << endl;
cout << fixed << showpoint << setprecision(2);
cout << "Start Balance: " << setw(9) << "$" << startbalance << "\n";
cout << "Total Deposits: " << setw(9) << "$" << totaldeposit << "\n";
cout << "Total Withdrawals: " << setw(9) << "$" << totalwithdrawal << "\n";
cout << "Total Interest Earned: " << setw(9) << "$" << totalinterest << "\n";
cout << "Final balance: " << setw(9) << "$" << monthend << "\n";
return 0;
}
Just type-cast your month variable to int before displaying.
cout << "Month #" << (int)month << endl;
That should fix your issue.
You can make monthend an int or a long. .........
Please make Data Type of your month as int instead of double.
double is a floating point data type. int is a whole number like 1, 2, 3, 4 and so on. Double is numbers with decimals like 1.1 or 45.564, float is a even more specific version of double
Example:
//if you just going to work with whole numbers
int a;
a = 1
//if you're working with numbers with a bit more precision
float b;
b = 1.1234
//if you're working with numbers with massive precision..
double c;
c = 1.123456
Your variable types seem to be fine for the calculation; I believe your problem is within this statement:
for (double month = 1; month <= 3; month++) {
cout << "Month #" << month << endl;
it is within your loop as why your month is printing out: 1.0, 2.0 etc.
change it to this:
for ( int month = 1; month <=3; month++ ) {
cout << "Month #" << month << endl;
Logically, variable month should be an integer.
Declare its datatype as int instead of double.
Hello so I am a new programming student and I am practicing for my final. I know my program has flaws, but the major flaw is when the user repeats the program the new calculations are added onto the previous ones. How would I correct it?
My code is below for this task:
// Andranik Keshishyan, Quiz 2
#include <iostream>
#include <string>
#include <iomanip> //For setw and other formatting
#include <ctime> //For random number generation
using namespace std;
int main()
{
bool repeat = true; //Repeats program if true
srand(time(0)); //Random number generation
double amount_thrown, dice1, dice2, sum1, sum2, sum3, sum4, avg1, avg2, avg3; //Variables
char space = ' '; //Space for Formatting
cout <<"This program will roll 2 dice and calculate their sum and average depending on the amount of throws\n";
cout <<"The amount of throws cannot exceed 12\n";
while (repeat){ //Will repeat program if true.
cout <<"How many times would you like the dice thrown?: ";
cin >> amount_thrown;
cout << "\n";
if ((amount_thrown < 1 || amount_thrown > 12)||(!(cin>>amount_thrown))){ //Checks to see if user input is valid.
cout <<"This is an invalid input of dice throws.\n";
}
else //Continues program if valid.
{
cout <<"Throw" << setw(3) << space <<"Die 1" << setw(3) << space << "Die 2" << setw(3) << space << "Sum\n";
for(int x=1; x<=amount_thrown; x++){ //Loops program until amount of throws equals to user input
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
sum1 = dice1+dice2; //Calculates sum of dice1 + dice 2
sum2 += dice1; //Calculates sum of all dice 1 throws
sum3 += dice2; // Calcules sum of all dice 2 throws
sum4 += sum1; // Calculates summ of the sum
avg1 = sum2/2; // Calculates avg of sum of dice 1 throws
avg2 = sum3/2; // Calculates avg of sum of dice 2 throws
avg3 = sum4/2; // Calculates ave of sum of dice 1 + dice 2
cout << setw(2) << x << setw(7) << dice1 << setw(8) << dice2 << setw(9) << sum1 << endl;
}
cout << "-------------------------------------\n";
cout << "Sum" << setw(5) << space << sum2 << setw(6) << space << sum3 << setw(6) << space << sum4 << endl;
cout << "Avg" << setw(5) << space << avg1 << setw(5) << space << avg2 << setw(5) << space << avg3 << endl;
}
cout << "\nWould you like to roll the dice again?[y=repeat / anything else=stop]: ";
char answer;
cin >> answer;
cin.ignore(1000, '\n'); //Makes sure other inputs are ignored
answer=tolower(answer);
repeat = answer == 'y'; //Program will repeat if user inputs true char y.
}
cout << "Thank you, goodbye" << endl;
return 0;
}
You are not resetting your sum2, sum3, and sum4 variables back to 0 on each iteration of the while loop. That is why their values are cumulative over repeats of the program.
In fact, you are not even initializing them at all, so the total sum will be random garbage anyway.
You need to reset them to 0 on each while iteration, before entering the for loop.
The solution is to place all code in a function like void userInput(); then in int main() have a while loop which calls userInput(); then system("CLR"); which allows you to reset.
I'm having an issue figuring out how to hide a specific variable (if that is even possible) in a cout function. Basically I need to do a number guess game, which would be easy enough except our teacher wants us to do it like a random math equation. Which... would honestly still be fairly easy except the way we have to do it is the program has to randomly create the problem and then randomly pick one of the 3 numbers to display and the user has to guess the other two missing numbers. For example if the program picked 20 + 32 = 52 it could potentially display __ + 32 = __.
I've gotten that far however I can't figure out how to make it so it displays like that but still allows me to put the line something like this
cout << num1 //Hidden << " + " << num2 << " = " << num3 //Hidden
However like I said I don't even know if that is possible if not then I will probably have to rewrite the whole program. This is what I have so far:
int main()
{
int num1, num2, num3, random1, guess1, guess2;
string play = "";
cout << "Would you like to run the number guessing program? (enter yes or no): ";
getline(cin, play);
for (int i = 0; i < play.length(); i++)
{
play[i] = tolower(play[i]);
}
//Random seed
srand(time(0));
while (play == "yes")
{
//Generate random numbers and num3
num1 = 1 + rand() % 50 + 1;
num2 = 1 + rand() % 50 + 1;
num3 = num1 + num2;
int pickRandom[3] = { num1, num2, num3 };
//Display random elements
random1 = pickRandom[rand() % 3];
if (random1 == num1){
cout << "\nYour randomly generated number problem: " << num1 << " + " << "__" << " = " << "__" << endl;
}
if (random1 == num2){
cout << "\nYour randomly generated number problem: " << "__" << " + " << num2 << " = " << "__" << endl;
}
if (random1 == num3){
cout << "\nYour randomly generated number problem: " << "__" << " + " << "__" << " = " << num3 << endl;
}
//Get Guesses
cout << "\nBased off of this information please make an educated guess as to what the two missing numbers are.";
cout << "\n\nGuess for number 1 (between 1 and 100): ";
cin >> guess1;
while ((guess1 > 100) || (guess1 < 0))
{
cout << "\nSorry you need to enter an integer between 1 and 100" << endl;
cout << "\nGuess for number 1 (between 1 and 100): ";
cin >> guess1;
}
cout << "\n\nGuess for number 2 (between 1 and 100): ";
cin >> guess2;
while ((guess2 > 100) || (guess2 < 0))
{
cout << "\nSorry you need to enter an integer between 1 and 100" << endl;
cout << "\nGuess for number 2 (between 1 and 100: ";
cin >> guess2;
}
if (guess1 == )
}
return 0;
}
I don't think you can hide variables in cout. But you can use a variable instead of hardcoding "__".
For instance, you can simply write this:
if(guessed_var1_correctly)
var1 = num1
else
var1 = "__"
if(guessed_var2_correctly)
var2 = num2
else
var2 = "__"
if(guessed_var3_correctly)
var3 = num3
else
var3 = "__"
cout << "\nYour randomly generated number problem: " << var1 << " + " << var2 << " = " << var3" << endl;
where var1, var2, var3 are output variables. If the player guesses it correctly, it'll display the actual value num1, num2, or num3. If not, it'll simply display "__".
So the code as is will run, however the calculations for the total and average variable are calculated when the firstE-fourthE variables are equal to 0. Surely there is a way to redefine them later in the code or recalculate them? I apologize for the horrible formatting and indents, this site is very picky.
#include <iostream>
using namespace std;
int main()
{
char fi = '\0', mi = '\0', li = '\0', end = '\0';
float firstE = 0,
secondE = 0,
thirdE = 0,
fourthE = 0,
total = firstE + secondE + thirdE + fourthE,
average = total / 4;
cout << "This program will calculate the average of a student's exam grades." << endl;
cout << "Please enter the first initial of the student's name: ";
cin >> fi;
cout << "Please enter the middle initial of the student's name: ";
cin >> mi;
cout << "Please enter the last initial of the student's name: ";
cin >> li;
cout << "Please enter the student's first exam score: ";
cin >> firstE;
cout << "Please enter the student's second exam score: ";
cin >> secondE;
cout << "Please enter the student's third exam score: ";
cin >> thirdE;
cout << "Please enter the student's fourth exam score: ";
cin >> fourthE;
/*float total = firstE + secondE + thirdE + fourthE,
average = total / 4;*/
cout << "Student's initials: " << fi << mi << li << endl;
cout << "Exam 1: " << firstE << endl;
cout << "Exam 2: " << secondE << endl;
cout << "Exam 3: " << thirdE << endl;
cout << "Exam 4: " << fourthE << endl;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
cin >> end;
}
Why are you doing the calculations BEFORE you've even got values to do the calculations with? Your code sequence should be:
1. define variables
2. get input from user
3. do calculations
4. present results
You're trying to eat your cake before you've even gone to the store to buy the eggs/milk/sugar, let alone mixing/baking it.
To get the desired behaviour from your code, you need to calculate the total and average after your inputs have been populated. Assuming that the grades are whole values, you can use ints to store each exam result:
#include <iostream>
int main()
{
char fi = '\0', mi = '\0', li = '\0', end = '\0';
int firstE = 0,
secondE = 0,
thirdE = 0,
fourthE = 0,
/*IO*/
float average = (firstE + secondE + thirdE + fourthE)/4;
/*IO*/
return 0;
}
This will provide you with working code.
We can clean it up further though. Why would we not be able to store John Edward Smith's initials as "JES" instead of inputting each character seperately?
#include <iostream>
#include <string>
int main()
{
std::string student_initials;
int firstE = 0,
secondE = 0,
thirdE = 0,
fourthE = 0,
std::cout << "This program will calculate the average of a student's exam grades." << endl;
std::cout << "Please enter the student's initials: ";
std::cin >> student_initials;
/*MORE IO*/
float average = (firstE + secondE + thirdE + fourthE)/4;
std::cout << "Student's initials: " << student_initials << std::endl;
/*MORE IO*/
return 0;
}
That's better, the interface to the user is a bit simpler. But what if a student took an extra exam? What if they only took 3? Either you can't input all their results, or the maths is wrong.
We can introduce a loop to the code that can handle the input of the results:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
/* STUFF */
int total;
int exam_result;
int exam_count = 1;
string input;
//this loop will capture multiple exam results (safely)
do
{
std::cout << "Please enter the results of exam #" << exam_count \
<< "\nleave blank if all results have been entered" << std::endl;
std::getline (std::cin, input);
stringstream(input) >> exam_result;
if (exam_result)
{
total += exam_result;
exam_count++;
}
} while (exam_result);
float average = total/exam_count;
/* STUFF */
return 0;
}
this captures multiple exam results (and totals and counts them) using a safe method of handling cin
It does however prevent you from printing out each individual result before the average but you can store them in a std::vector and iterate through them to do that. I'll leave that up to you.
Final code:
#include <iostream>
#include <string>
#include <sstream>
int main()
{
std::string student_initials;
std::cout << "This program will calculate the average of a student's exam grades." << endl;
std::cout << "Please enter the student's initials: ";
std::cin >> student_initials;
int total;
int exam_result;
int exam_count = 1;
string input;
//this loop will capture multiple exam results (safely)
do
{
std::cout << "Please enter the results of exam #" << exam_count \
<< "\nleave blank if all results have been entered" << std::endl;
std::getline (std::cin, input);
stringstream(input) >> exam_result;
if (exam_result)
{
total += exam_result;
exam_count++;
}
} while (exam_result);
float average = total/exam_count;
std::cout << "Student's initials: " << student_initials << std::endl;
cout << "Total: " << total << endl;
cout << "Average: " << average << endl;
return 0;
}
How do I define a variable or recalculate it later in the code?
Like this
#include <iostream>
int main()
{
int a; // define it once
int b; // define it once
int c; // define it once
int total; // define it once
a = 2; // change its value
b = 4;
c = 1;
total = a + b + c; // or calculate its value
std::cout << "total: " << total << '\n';
a = 9; // change its value AGAIN
b = 1;
c = 12;
total = a + b + c; // and calculate its value AGAIN
std::cout << "total: " << total << '\n';
}