How do i store the output from cout into a variable - c++

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.

Related

How do you print multiple floats from user input and have only some of them with specific decimal places?

I am trying to print multiple floats, but only some of them need to be a specific decimal place. The user will input two float values, a width and a height. Then the program will calculate the perimeter and area with the two values. Then it will print the values plugged into the equations and show the answer with only one decimal place.
So, an example would look like this:
Width: 3.14
Height: 4.2
Area: 3.14 * 4.2 = 13.2
Perimeter: 2 * (3.14 + 4.2) = 14.7
The issue I am having is that when I go to print the output, I can't get it to print the exact values of the floats that the user inputs and have it print out the answers with only one decimal place. I've tried using setprecision as well as printf, but I just can't get it to work. I tried following answered questions about showing exact decimal places, but nothing has been meeting what I need to do. Here's my code (Sorry if it's sloppy):
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float width = 0;
float height = 0;
cout << "Rectangle Calculator" << endl;
cout << "Please enter the width: ";
cin >> width;
cout << "Please enter the height: ";
cin >> height;
float area = width * height;
float perimeter = 2 * (width + height);
cout << "Area: " << width << " * " << height << " = " << fixed << setprecision(1) << area << endl;
cout << "Perimeter: 2 * (" << width << " + " << height << ")" << " = " << fixed << setprecision(1) << perimeter;
return 0;
}
if I understand you correctly you want to print out with the precision that the user used for the input. you can achieve this by first saving the input in a std::string and count the precision from there. Using the greatest precision from the 2 inputs.
#include <iostream>
#include <iomanip>
#include <sstream>
#include <string>
bool is_valid_float(std::string str) {
std::istringstream iss(str);
float test;
iss >> std::noskipws >> test;
return iss.eof() && !iss.fail();
}
unsigned get_precision(std::string input) {
for (unsigned i = 0u; i < input.length(); ++i) {
if (input[i] == '.') {
return (input.length() - i - 1);
}
}
return 0u;
}
int main() {
float width = 0;
float height = 0;
std::cout << "Rectangle Calculator\n\n";
std::string input;
do {
std::cout << "Please enter the width: ";
std::cin >> input;
if (!is_valid_float(input)) {
std::cout << "invalid input\n";
}
else {
break;
}
} while (true);
unsigned max_precision = get_precision(input);
width = std::atof(input.c_str());
do {
std::cout << "Please enter the height: ";
std::cin >> input;
if (!is_valid_float(input)) {
std::cout << "invalid input\n";
}
else {
break;
}
} while (true);
max_precision = std::max(max_precision, get_precision(input));
height = std::atof(input.c_str());
float area = width * height;
float perimeter = 2 * (width + height);
std::cout << "\nArea: " << width << " * " << height << " = " << std::fixed << std::setprecision(max_precision) << area << '\n';
std::cout << "Perimeter: 2 * (" << width << " + " << height << ")" << " = " << std::fixed << std::setprecision(max_precision) << perimeter << '\n';
}
example run:
Rectangle Calculator
Please enter the width: 3.4
Please enter the height: 1.5
Area: 3.4 * 1.5 = 5.1
Perimeter: 2 * (3.4 + 1.5) = 9.8
Rectangle Calculator
Please enter the width: 15.125
Please enter the height: 22.0875
Area: 15.125 * 22.0875 = 334.0734
Perimeter: 2 * (15.1250 + 22.0875) = 74.4250
note that float has only about 7.225 correct decimal places:
Rectangle Calculator
Please enter the width: 2.1111111111111
Please enter the height: 3.9999999999999
Area: 2.11111 * 4 = 8.4444446563721
Perimeter: 2 * (2.1111111640930 + 4.0000000000000) = 12.2222223281860
so you should use double instead of float in your program. it achieves 15.955 correct decimal places.

Variable may be uninitialized/is used uninitialized

I'm writing an English-Metric converter program in C++, and I'm trying to use try, throw, catch to reject negative/non-numeric values in the 'main' function.
My two problems are:
1.)
Whenever I enter, say, 'g' into the console, I get an output: 0 inches is equal to 0 centimeters AND THEN I get the error display that I want to pop up. What i need is only the error display to be output.
2.) When I enter a negative number, like -3, I get the proper conversion as a negative number when I would like it to tell me my input is invalid.
Here is my code.
#include <iostream>
#include <cctype>
char menuSelect();
using namespace std;
int main(int argc, const char * argv[])
{
double inches;
double centimeters;
char select;
try
{
do
{
if (centimeters < 0.0 || inches < 0.0)
throw 0;
if (!cin)
throw 0;
select = menuSelect();
if (select == 'E')
{
cout << "Enter the number of inches: ";
cin >> inches;
centimeters = inches * 2.54;
cout << inches << " inches is equal to " << centimeters
<< " centimeters." << endl;
}
else if (select == 'M')
{
cout << "Enter the number of centimeters: ";
cin >> centimeters;
inches = centimeters / 2.54;
cout << centimeters << " Centimeters is equal to " << inches
<< " inches." << endl;
}
} while (select != 'Q');
}
catch (int errID)
{
cout << "Error: " << errID << endl;
cout << "Please enter a positive number. ";
}
return 0;
}
It should be something like that: (I added a flag bool bNeg = false, if (inches>=0) and if (centimeters>=0) just after the input & if the input is negative for either 'E' or 'M' set bNeg = true)
bool bNeg = false;
if (select == 'E')
{
cout << "Enter the number of inches: ";
cin >> inches;
if (inches>=0) { // No meaning to negative values
centimeters = inches * 2.54;
cout << inches << " inches is equal to " << centimeters
<< " centimeters." << endl;
}
else bNeg = true;
}
else if (select == 'M')
{
cout << "Enter the number of centimeters: ";
cin >> centimeters;
if (centimeters>=0) { // No meaning to negative values
inches = centimeters / 2.54;
cout << centimeters << " Centimeters is equal to " << inches
<< " inches." << endl;
}
else bNeg = true;
}
if (bNeg) {
// tbd: say what you want to say
}

How to Calculate How Many Times Inputs Entered in Sentinel Loop c++

Here is the link to the programming question for detail. I have done my source code but I don't know how to calculate and display how many times inputs are entered in sentinel loop. Here is my source code:
#include <iostream>
using namespace std;
int main() {
int i, hours;
int tot_clients = 0;
float charges;
float tot_collection = 0;
const int sentinel = -1;
cout << "Welcome to ABC Parking Services Sdn Bhd" << endl;
cout << "=======================================" << endl;
while (hours != sentinel) {
cout << "Please enter number of parking hours (-1 to stop)" << endl;
cin >> hours;
if (hours <= 2 && hours > 0) {
charges = 1.00 * hours;
cout << "Charges: " << charges << endl;
}
else if (hours > 2 && hours <= 12) {
charges = (1.00 * 2) + ((hours - 2) * 0.50);
cout << "Charges: " << charges << endl;
}
else if (hours > 12) {
charges = 10.00 * hours;
cout << "Charges: " << charges << endl;
}
else if (hours == sentinel) {
break;
}
tot_collection = tot_collection + charges;
}
cout << "SUMMARY OF REPORT" << endl;
cout << "=======================================" << endl;
cout << "Total clients:" << tot_clients << endl;
cout << "Total colletion:" << tot_collection << endl;
return 0;
}
Hope someone can help me solving this. I am studying for my programming final exam.
I understand you want to count the number of clients (tot_clients). You have already intitalised the tot_clients = 0. This is good. You just have to increment the tot_clients variable inside the while loop (tot_clients++).
while (hours != sentinel)
{
cout << "Please enter number of parking hours (-1 to stop)" << endl;
cin >> hours;
tot_clients++; //this is the code to be added
/*rest of the code remains same*/
Add tot_clients++; just before or after tot_collection = tot_collection + charges;
1- initialize hours=0 otherwise hour will have some undetermined value during first-time condition check of while loop.
2-i am assuming that tot_clients stores total no. of customers than,
you just need to increment tot_clients on each iteration
#include <iostream>
using namespace std;
int main()
{
int i, hours=0;
int tot_clients=0;
float charges;
float tot_collection=0;
const int sentinel = -1;
cout << "Welcome to ABC Parking Services Sdn Bhd" << endl;
cout << "=======================================" << endl;
while (hours != sentinel)
{
cout << "Please enter number of parking hours (-1 to stop)" << endl;
cin >> hours;`
if (hours <= 2 && hours >0)
{
charges = 1.00 * hours;
cout << "Charges: " << charges << endl;
}
else if (hours>2 && hours <=12)
{
charges = (1.00*2) + ((hours - 2) * 0.50);
cout << "Charges: " << charges << endl;
}
else if (hours > 12)
{
charges = 10.00 * hours;
cout << "Charges: " << charges << endl;
}
else if (hours == sentinel)
{
break;
}
tot_collection = tot_collection + charges;
tot_clients=tot_clients+1; //increment's on each iteration except on input -1
}
cout << "SUMMARY OF REPORT" << endl;
cout << "=======================================" << endl;
cout << "Total clients:" << tot_clients << endl;
cout << "Total colletion:" << tot_collection << endl;
return 0;
}
`

Code WORKS Math DOESN'T

My code compiles nicely, but the math formulas that I am using aren't providing the right outcome. I need to calculate the balance, withdrawn, and interest for all 3 months. I am also required to validate user's input. For these purposes I am using nested loops. Please let me know if you spot my mistake. Thank you lovely people!
cout << "Please enter the starting balance: ";
cin >> startBalance;
cout << "Please enter the annual interest rate: ";
cin >> annualInterest;
for (int month = 1; month <= 3; month++) {
do {
cout << setprecision(5);
cout << "Please enter the total amount deposited on month " << month << ": ";
cin >> balance;
if (balance <0) {
goodChoice = false;
cout << "\n\t***ERROR " << balance << " ***";
cout << "*** Choice must be positive***\n" << endl;
}
else {
goodChoice = true;
}
startBalance += balance; //need to calculate the balance for all 3 months
} while (!goodChoice);
do {
cout << setprecision(5);
cout << "Please enter the total amount withdrawn on " << month << ": ";
cin >> withdrawn;
if ( (withdrawn <0) || (withdrawn > startBalance) ) {
goodChoice = false;
cout << "***ERROR " << withdrawn << " ***";
cout << "*** Choice must be positive or greater than the balance***" << endl;
}
else {
goodChoice = true;
}
finalWithdrawn += withdrawn; // the total amount of withdrawn
finalBalance = startBalance - withdrawn;
monthInterest = ((startBalance + finalBalance) / 2) * (annualInterest / 12);
totalInterest += monthInterest; //total interest for all 3 months
endBalance = monthInterest + finalBalance;
} while (!goodChoice);
}
cout << "Total Deposit: " << endBalance << endl;
cout << "Total Withdrawn: " << finalWithdrawn << endl;
cout << "Total Interest: " << totalInterest << endl;
cout << "Final Balance: " << endBalance << endl;
You have a lot of extra variables defined which aren't needed. Also, your interest rate may have been in percentage instead of a decimal number, i.e. 10% = 0.1. Also, your monthInterest is taking an average then applying interest. I wrote this up and it seems to work.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float totalDeposit = 0.0f;
float totalWithdrawn = 0.0f;
float totalInterest = 0.0f;
float totalBalance = 0.0f;
float interestRate = 0.0f;
setprecision(5); //?
cout << "Enter starting balance: ";
cin >> totalBalance;
cout << "Enter annual interest rate (%): ";
cin >> interestRate;
// Convert to monthly and non-percent; i.e. 10% = 0.1 = 10 / 100
interestRate = interestRate / 100.0f / 12.0f;
for (int month = 1; month <= 3; month++)
{
float deposit = -1.0; // Default to an error state
while (deposit < 0.0)
{
cout << "Enter total deposited in month " << month << ": ";
cin >> deposit;
if (deposit < 0.0f)
{
cout << "ERROR: Invalid amount" << endl;
continue;
}
}
float withdrawn = -1.0f; // Default to an error state
while (withdrawn < 0.0f)
{
cout << "Enter total withdrawn in month " << month << ": ";
cin >> withdrawn;
if (withdrawn < 0.0f)
{
cout << "ERROR: Invalid amount" << endl;
continue;
}
}
totalDeposit += deposit;
totalWithdrawn += withdrawn;
totalBalance = totalBalance + deposit - withdrawn;
totalBalance += totalBalance * interestRate;
totalInterest += totalBalance * interestRate;
}
cout << "Total Deposit: " << totalDeposit << endl;
cout << "Total Withdrawn: " << totalWithdrawn << endl;
cout << "Total Interest: " << totalInterest << endl;
cout << "Final Balance: " << totalBalance << endl;
int wait; // Pause so console window doesn't close. Delete this line.
cin >> wait;
return 0;
}

How do you add 2 decimal places to numbers?

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.