sI am learning C++ and I keep getting a strange error. setprecision is giving me multiple decimal points in the one answer.
Why doe the output have multiple decimal points?
Program
#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
int main () {
int time, counter, range;
double investment, rate, balance;
cout << "Investment amount: " << endl;
cin >> investment;
cout << "Rate: " << endl;
cin >> rate;
cout << "Length of time: " << endl;
cin >> time;
cout << "Incremental Range: " << endl;
cin >> range;
balance = 0;
counter = 0;
cout << "\n\n\nRate \t 5 Years \t 10 Years \t 15 Years \t 20 Years \t 25 Years \t 30 Years \n" << endl;
cout << fixed << setprecision(2);
while(counter < 6)
{
counter = counter + 1;
balance = investment * pow((1+ rate/100), time);
cout << setw(2) << rate << setw(12) << balance;
time = time + range;
}
cout << endl;
return 0;
}
Output
Rate 5 Years 10 Years 15 Years 20 Years 25 Years 30 Years
5.00 1276.285.00 1628.895.00 2078.935.00 2653.305.00 3386.355.00 4321.94
As you can see 1276.285.00 etc should be 1276.28.
Why does the output have multiple decimal points?
I don't think you want to write rate each iteration:
cout << setw(2) << rate << setw(12) << balance;
The last part of "double-decimal-point" number is your rate.
Related
This question already has answers here:
How to test whether stringstream operator>> has parsed a bad type and skip it
(5 answers)
How Can I avoid char input for an int variable?
(4 answers)
Closed 5 months ago.
I am trying to make an employee discount program that reads employee number and discount from an input file. I need it to display an error message when a character is put into the variable. I can't seem to figure this out. I'm a newbie so I don't know that many identifiers yet. This compiles with an unexpected output. I'm not sure how to get the variables for all three employees as well. Any help is greatly appreciated.
/* Program name: main.cpp
* Author: Carl Snyder
* Date last updated: 09/11/2022
* Purpose: Top employee discount calculator
*/
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream inFile;
int winning_Num;
int employee_Num;
double total_Bill;
double discount_Percent;
double discount_Amount;
double bill_After_Discount;
inFile.open("EOM.txt");
inFile >> winning_Num >> discount_Percent;
cout << "Enter your employee number to see if you get a discount: ";
cin >> employee_Num;
cout << fixed << showpoint << setprecision(2);
if (employee_Num >= 10000 && employee_Num <= 99999)
{
if (employee_Num == winning_Num)
{
cout << "You have won a discount of " << discount_Percent << "%." << endl;
cout << "Enter the total bill: " << endl;
cin >> total_Bill;
if (total_Bill > 0)
{
discount_Amount = total_Bill * discount_Percent;
bill_After_Discount = total_Bill - discount_Amount;
cout << "Your discount will take $" << discount_Amount << " off your bill. "
<< endl;
cout << "Your new total is $" << bill_After_Discount << "." << endl;
return 0;
}
if (total_Bill <= 0)
{
cout << "The total should be greater than 0. The program will now
exit.";
}
else
cout << "You entered something that is not a number! The program will
now exit.";
}
else
cout << "Sorry you did not win a discount this month. Try again next
month.";
}
if (employee_Num <=9999 || employee_Num >=100000)
{
cout << "You entered a number that is out of range! Employee numbers are 5
digits (between 10000 and 99999). Program will now exit.";
}
else
cout << "You did not enter a number! The program will now exit.";
return 0;
}
This question already has answers here:
Why does std::getline() skip input after a formatted extraction?
(5 answers)
Closed 4 years ago.
Good day,
I was writing this code for a school project, but after compiling and executing it, after hitting yes, I was unable to enter a name.
I am not sure why this is happening, happened to both codeblocks and vs community.
I've tried adding cin.ignore(); below getline(cin, customer) and it kinda works but I am not able to enter the name of a business. If I put cin.ignore() on both, the enter number field will be skipped and it will go directly to the results.
I will attach an image below (without using cin.ignore)
#include "pch.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
string input;
cout << "hello, press yes to start or no to cancel \n";
cin >> input;
if (input == "no")
{
cout << "have a nice day \n";
}
else if (input == "yes")
{
string customer;
string address;
int user_enter_number;
const double pc = 0.05 * 10;
double amount, abacus, price; // abacus = AMOUNT
time_t now; // rawtime
struct tm nowlocal;
cout << "Please enter your name " << endl;
getline(cin, customer); ` when executing, I was not able to type my
name and instead was skipped and went to
enter the store's name.`
cout << "Please enter the store's name \n";
getline(cin, address);
cout << "Please enter the number you would like to buy, the range is
from 00 - 99 \n";
cin >> user_enter_number;
cout << "Please enter the amount you wish to spend ($): \n";
cin >> amount;
abacus = amount * pc;
price = amount;
now = time(NULL); // obtains the time from the operating system
nowlocal = *localtime(&now);
cout << customer << " you have bought this number: " <<
user_enter_number << endl;
cout << "you have bought this pcs: " << amount / 0.05 << endl;
cout << "this ticket was bought on: " << nowlocal.tm_mday << "/" <<
nowlocal.tm_mon + 1 << "/" << nowlocal.tm_year + 1900 << endl;
cout << "at this time: " << nowlocal.tm_hour << ":" << nowlocal.tm_min << ":" << nowlocal.tm_sec << endl;
srand(time(NULL));
int min = 00;
int max = 99;
int num = (min + (rand() % (int)(max - min + 1)));
cout << "the winning number is: " << num << endl;
if (num == user_enter_number)
{
cout << customer << " You have won" << amount << "Please visit your
nearest store to collect! \n";
}
else
{
cout << "Try again next time! \n";
}
return 0;
}
The first line of input is a line. Use getline for that too.
cin >> input;
Leaves the newline in the buffer.
getline(cin, customer);
Only gets to read the newline from the first input.
I'm trying to do this program for many hours, but I couldn't.
The question is I've to take some amount of money from user. Then I've to ask how many 5s he have and how many 2s he have. I've to convert that amount of money to 5s and 2s and 1s. User have unlimited source of 1s. In short if user enters 27 I've to tell him 5 5s and 1 2s.
Now i did this type of program in which I converted time(from seconds to years and so on)
Now I did this in program:-
int money;
cout << "How much amount of money= ";
cin >> money;
cout << endl;
int ao5;
cout << "how many number of 5 coins available in your drawer= ";
cin >> ao5;
cout << endl;
int ao2;
cout << "how many number of 2 coins available in your drawer= ";
cin >> ao2;
cout << endl;
int fchange, tchange, ochange;
ochange = (money / 1) % ao5%ao2;
tchange = (money / ao2) % ao5;
fchange = money / ao5;
cout << " " << fchange;
cout << " " << tchange;
cout << " " << ochange;
I've tried other methods. I tried dividing money by 5 and then subtract it with 5s I've but it makes no sense.
Can anyone just take me to right path?
You can use this
void divid(int num){
if(num>=5){
int remainderAfterdevidingTo5 = num%5;
int numOf5s = num/5;
std::cout << " numOf5s "<< numOf5s<< std::endl;
divid(remainderAfterdevidingTo5);
}else if(num>=2){
int remainderAfterdevidingTo2 = num%2;
int numOf2s = num/2;
std::cout << " numOf2s "<< numOf2s<< std::endl;
divid(remainderAfterdevidingTo2);
}else if(num>=1){
std::cout << " numOf1s " <<num<< std::endl;
}
}
This code is used to run a loop three times, that takes the numbers of eggs gathered and outputs the number in dozens and extra until the user enters a negative number. Then, it prints out the average amount of eggs gathered (entered), and outputs the total number of dozens and extra.
The inputs we were assigned to use are:
43,
31,
-1,
24,
8,
14,
-999,
-5.
Everything is fine up until we input -5. Our teacher doesn't want the average or total number of dozens and extras to print (you'll see what I mean in the output).
The source code is as follows:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int eggNum;
int eggDozens;
int eggExtra;
int eggTotal;
int loopCount;
int forCount;
float eggAvg;
int totalDozens;
int totalExtra;
for(forCount = 1; forCount <= 3; forCount=forCount + 1)
{
cout << left << "TEST #" << forCount << ":" << endl;
cout << "Welcome to Aunt Ellen\'s eggs to dozens converter!";
cout << endl << endl;
cout << "\tEnter the number of eggs gathered: ";
cin >> eggNum;
eggTotal = 0;
loopCount = 0;
while(eggNum >= 0)
{
eggDozens = eggNum / 12;
eggExtra = eggNum % 12;
if(eggDozens != 0)
{
if(eggExtra != 0)
{
cout << "\tYou have " << eggDozens << " dozen ";
cout << eggExtra << " eggs.";
cout << endl << endl;
}
else
{
cout << "\tYou have " << eggDozens << " dozen eggs.";
cout << endl << endl;
}
}
else
{
cout << "\tYou have " << eggExtra << " eggs.";
cout << endl << endl;
}
loopCount = loopCount + 1;
eggTotal = eggTotal + eggNum;
cout << "\tEnter the number of eggs gathered: ";
cin >> eggNum;
}
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
cout << "\tOn average " << eggAvg << " eggs have been";
cout << " gathered.";
totalDozens = eggTotal / 12;
totalExtra = eggTotal % 12;
cout << endl << "\tA total of " << totalDozens << " dozen ";
cout << totalExtra << " and eggs have been gathered!" << endl;
cout << endl << endl;
}
return 0;
}
And the output:
TEST #1:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: 43
You have 3 dozen 7 eggs.
Enter the number of eggs gathered: 31
You have 2 dozen 7 eggs.
Enter the number of eggs gathered: -1
TOTALS:
On average 37 eggs have been gathered.
A total of 6 dozen 2 and eggs have been gathered!
TEST #2:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: 24
You have 2 dozen eggs.
Enter the number of eggs gathered: 8
You have 8 eggs.
Enter the number of eggs gathered: 14
You have 1 dozen 2 eggs.
Enter the number of eggs gathered: -999
TOTALS:
On average 15.3333 eggs have been gathered.
A total of 3 dozen 10 and eggs have been gathered!
TEST #3:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: -5
TOTALS:
On average -1.#IND eggs have been gathered.
A total of 0 dozen 0 and eggs have been gathered!
I don't want the very last "TOTALS" and the lines following. I want the program to terminate after entering -5.
The simplest thing is to do this before entering the while loop:
cin >> eggNum;
if (eggNum < 0)
break ;
That will quit the for loop, and return 0;
You may, if you want to, add some comments to the caller about entering negative numbers before calling break.
You mentioned that you only want to omit the last block of TOTALS.
You can simply add a special case to leave the outer loop early in this case.
Right before this block, but after the closing brace of the while loop.
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
Insert this:
if (forCount == 3) break;
If you just want to avoid printing whenever the average is less than 0, then instead you should insert in the same location.
if (eggAvg < 0) continue;
This will skip the rest of that iteration of the for loop.
I think a simple answer to your problem would be to just put an if statement around the printing total code. Like this:
if(eggNum > -5){ //won't print for negative 5
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
cout << "\tOn average " << eggAvg << " eggs have been";
cout << " gathered.";
totalDozens = eggTotal / 12;
totalExtra = eggTotal % 12;
cout << endl << "\tA total of " << totalDozens << " dozen ";
cout << totalExtra << " and eggs have been gathered!" << endl;
cout << endl << endl;
}
I hope this helps!
I've been teaching myself C++ on and off for a few months and now I'm trying to make a payroll system. Here's my code:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void wageCompute (int, int);
int main()
{
int loopTimes=0;
int empNum=100, workHours, otHours, rate, bPay, otPay, grossPay;
string empName, empPos;
cout << "PAYROLL FOR THE MONTH OF MARCH" << endl;
cout << "Employees: " << empNum << endl;
while (empNum>loopTimes)
{
cout << "NAME: ";
cin.ignore();
getline (cin, empName);
cout << "\nPOSITION: ";
getline (cin, empPos);
cout << "\nHOURS WORKED: ";
cin >> workHours;
cout << "\nWAGE PER HOUR: ";
cin >> rate;
bPay = workHours*rate;
cout << "YOUR BASE PAY IS: " << bPay << endl << endl;
cout << "HOURS WORKED OVERTIME: ";
cin >> otHours;
otPay = (1.5*rate)*otHours;
cout << "\nOVERTIME PAY: " << otPay << endl;
grossPay = bPay + otPay;
cout << "GROSS PAY: " << grossPay << endl;
wageCompute(bPay, grossPay);
loopTimes++;
}
return EXIT_SUCCESS;
}
void wageCompute(int bPay, int grossPay)
{
double rate, dedInsurance, dedMedical, totDeduct, netPay, tax;
if (bPay<10001)
{
rate = 0.05;
}
else if (bPay<15001)
{
rate = 0.1;
}
else if (bPay<20001)
{
rate = 0.15;
}
else
{
rate = .2;
}
tax = bPay*rate;
dedInsurance = bPay*0.05;
dedMedical = bPay*0.01;
totDeduct = tax + dedInsurance + dedMedical;
cout << "TAX: " << tax << endl;
cout << "SSS DEDUCTION: " << dedInsurance << endl;
cout << "Medicare DEDUCTION: " << dedMedical << endl;
cout << "TOTAL DEDUCTIONS: " << totDeduct << endl;
netPay = grossPay - totDeduct;
cout << "NET PAY: " << netPay << endl;
}
The part where it goes wrong is when I input a certain value for the Hours Worked, Wage per Hour and Hours worked overtime. The program checks the basic pay for the suitable amount of tax it should deduct, what I input was 160 for the hours worked, 100 for the wage per hour, and 10 for overtime. I've tried lessening and increasing it and it worked just fine it seems that it's just these combination of numbers is the part where it goes wrong.
A screenshot of the output:
Your question isn't very clear but I suspect that what you are seeing here is a well known limitation of floating point numbers; numbers that are easy to represent exactly in base 10 don't have an exact representation in base 2. One example : 0.1 in base 10 is 0.0001100110011… repeating in base 2; the accuracy of the approximation depends on how many bits one is willing to use to write it.
An alternative approach is to use integer arithmetic with a known precision, so say you want to calculate to the nearest hundredth of a penny (I'm using UK currency here). Represent £1.01 as 10100 and when your finished val / 10000 is the pounds and (val % 10000) / 100 is the pence. If needed you can implement some more complex rules around rounding for the pence.