I have written a C++ program (supposed to be a money counter), I'm having some trouble with my code, I need the decimals to show up. I use cout instead of printf if that matters.
#include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
// Strings and Integers
int dollars;
int pennies;
int nickles;
int quarters;
int halfDollars;
int dimes;
int fiveBill;
int tenBill;
int twentyBill;
int fiftyBill;
int hundredBill;
// Coin/Bill Amounts
int penny = 0.01;
int dollar = 1.00;
int nickle = 0.05;
int quarter = 0.25;
int halfDollar = 0.50;
int dime = 0.10;
int five = 5.00;
int ten = 10.00;
int twenty = 20.00;
int fifty = 50.00;
int hundred = 100.00;
// Enter Amount
cout << "Count your money!\n\n" << endl << "Hundred Dollar Bills: ";
cin >> hundredBill;
cout << "\nFifty Dollar Bills: ";
cin >> fiftyBill;
cout << "\nTwenty Dollar Bills: ";
cin >> twentyBill;
cout << "\nTen Dollar Bills: ";
cin >> tenBill;
cout << "\nFive Dollar Bills: ";
cin >> fiveBill;
cout << "\nOne Dollar Bills: ";
cin >> dollars;
cout << "\nHalf-Dollars: ";
cin >> halfDollars;
cout << "\nQuaters: ";
cin >> quarters;
cout << "\nDimes: ";
cin >> dimes;
cout << "\nNickles: ";
cin >> nickles;
cout << "\nPennies: ";
cin >> pennies;
// Add Together
cout << (hundred * hundredBill) + (fifty * fiftyBill) + (twenty * twentyBill) + (ten * tenBill) + (five * fiveBill) + (dollars * dollar) + (halfDollar * halfDollars) + (quarter * quarters) + (dime * dimes) + (nickle * nickles) + (penny * pennies);
system("PAUSE");
return 0;
}
Your problem:
int penny = 0.01;
penny is an int, the name is short for 'integral value'. 0.01 is of type double. If you assign a double (either as literal or from another variable) to any form of int (int, long int, short int, ...), only the integral part is assigned and the decimals are dropped (simply dropped, no rounding occurs - no matter how close the value is to the next greater integral one).
So penny actually holds only 0. Alike the other variables, dollar is 1, nickle again 0, ...
You have now two choices. Either, you convert all numbers to double, or you do a little trick by assigning all values in cents:
int penny = 1;
int dollar = 100;
This is what I would prefer. Then only when it comes to outputting you would do appropriate formatting:
printf("the value of my variable is %d.%.2d $\n", value / 100, value % 100);
Edit:
As many prefer outputting via std::cout and this gets rather a hassle, a way to do it conveniently would be the following:
class Formatter
{
int value;
friend std::ostream& operator<<(std::ostream& s, Formatter f);
public:
Formatter(int value)
: value(value)
{
}
};
typedef Formatter F, M;
std::ostream& operator<<(std::ostream& s, Formatter f)
{
char c = s.fill();
return s << f.value / 100 << '.'
<< std::setfill('0') << std::setw(2) << f.value % 100
<< std::setfill(c); // restore previous fill character!
}
Typedef is not necessary, of course, just to illustrate other names – select any one that seems most appropriate to you (F: Formatter, M: Money, D: Dollar, ...). Usage then:
std::cout << F(penny) << std::endl;
As stated, the problem is that you are trying to assign a decimal value to an integer variable.
What occurs, is that your input (in the case of decimal values) can either be interpreted as a double or a float -type variable by the compiler. During the assignment of the given input however, int or fully, an integer, can only hold a value without a fractional component. Compiler takes note of this, and simply narrows your given input into a value the int variable can hold. The compiler isn't interested about anything after the decimal point, and simply discards the rest.
Thus,
int a = 3.5 // int can't hold the decimal 0.5, narrows into 3
int b = 3 // int can hold this, no narrowing
double d = 3.5 // double can hold this, no narrowing
float f = 3.5 // float can hold this, no narrowing
A good way would be to replace all your integer variables with the type double. In this simple a program, you shouldn't have the need to use printf to format the input.
And in the case you are wondering, why would I want to use double instead of float.
Here is some additional information:
https://softwareengineering.stackexchange.com/questions/188721/when-do-you-use-float-and-when-do-you-use-double
Should I use double or float?
If you want to keep integers, cast the result to a float or double. Then set precision to 2 digits and fixed format.
#include <iostream>
#include <iomanip>
...
float total = (float) ((hundred * hundredBill) + (fifty * fiftyBill) + (twenty * twentyBill) + (ten * tenBill) + (five * fiveBill) + (dollars * dollar) + (halfDollar * halfDollars) + (quarter * quarters) + (dime * dimes) + (nickle * nickles) + (penny * pennies));
cout << std::setprecision(2) << std::fixed << total << endl;
I use "cout" instead of "printf" if that matters.
No it won't matter with whatever output you were expecting.
Use all the variables you want to manipulate w.r.t. decimals as 'double' data type.
Related
why it is printing as cout<<(4*(double)(r*r))<<endl; as integer as something wrong with my typecast.
I have to take input r as an int
input->1 output->4
and why
cout<<setprecision(2)<<ab2<<endl; rounding the answer at least it should give correct answer till two digits because i have set set precision 2
input->1 output->3.8
#include<bits/stdc++.h>
using namespace std;
int main(){
int t;
cin>>t;
while(t--){
long long int r;
cin>>r;
double ab2 = 4*(double)(r*r) - double(0.25);
cout<<4*(double)(r*r)<<endl;
cout<<setprecision(2)<<ab2<<endl;
cout<<ab2+0.25<<endl;
}
}
I'm guessing you're going to see something more like what you are expecting with this code
int main() {
cout << fixed << setprecision(2); // fixed notation and two decimal places
int t;
cin >> t;
while (t--) {
long long int r;
cin >> r;
double ab2 = 4 * (double)(r*r) - double(0.25);
cout << 4 * (double)(r*r) << endl;
cout << ab2 << endl;
cout << ab2 + 0.25 << endl;
}
}
Input
1 1
Output
4.00
3.75
4.00
why it is printing as cout<<(4*(double)(r*r))<<endl; as integer as
It is a double, so it is printing it as a double. It is however a double that represents a whole number.
and why
cout<<setprecision(2)<<ab2<<endl; rounding the answer
Because you've used smaller precision than the value has significant digits.
#include <iostream>
#include <cmath>
using namespace std;
/* FINDS AND INITIALIZES TERM */
void findTerm(int t) {
int term = t * 12;
}
/* FINDS AND INITIALIZES RATE */
void findRate(double r) {
double rate = r / 1200.0;
}
/* INITALIZES AMOUNT OF LOAN*/
void findAmount(int amount) {
int num1 = 0.0;
}
void findPayment(int amount, double rate, int term) {
int monthlyPayment = amount * rate / ( 1.0 -pow(rate + 1, -term));
cout<<"Your monthly payment is $"<<monthlyPayment<<". ";
}
This is the main function.
int main() {
int t, a, payment;
double r;
cout<<"Enter the amount of your mortage loan: \n ";
cin>>a;
cout<<"Enter the interest rate: \n";
cin>>r;
cout<<"Enter the term of your loan: \n";
cin>>t;
findPayment(a, r, t); // calls findPayment to calculate monthly payment.
return 0;
}
I ran it over and over again, but it still gives me the incorrect amount.
My professor gave us an example that goes like this:
Loan=$200,000
Rate=4.5%
Term: 30 years
And the findFormula() function is supposed to produce $1013.67 for the mortgage payment. My professor gave us that code as well (monthlyPayment = amount * rate / ( 1.0 – pow(rate + 1, -term));). I'm not sure what's wrong with my code.
The formula may be fine, but you are not returning, nor using, any value from your conversion functions, so its inputs are wrong.
Consider this refactoring of your program:
#include <iostream>
#include <iomanip> // for std::setprecision and std::fixed
#include <cmath>
namespace mortgage {
int months_from_years(int years) {
return years * 12;
}
double monthly_rate_from(double yearly_rate) {
return yearly_rate / 1200.0;
}
double monthly_payment(int amount, double yearly_rate, int years)
{
double rate = monthly_rate_from(yearly_rate);
int term = months_from_years(years);
return amount * rate / ( 1.0 - std::pow(rate + 1.0, -term));
}
} // end of namespace 'mortgage'
int main()
{
using std::cout;
using std::cin;
int amount;
cout << "Enter the amount of your mortage loan (dollars):\n";
cin >> amount;
double rate;
cout << "Enter the interest rate (percentage):\n";
cin >> rate;
int term_in_years;
cout << "Enter the term of your loan (years):\n";
cin >> term_in_years;
cout << "\nYour monthly payment is: $ " << std::setprecision(2) << std::fixed
<< mortgage::monthly_payment(amount, rate, term_in_years) << '\n';
}
It still lacks any checking of the user inputs, but given the values of your example, it outputs:
Enter the amount of your mortage loan (dollars):
200000
Enter the interest rate (percentage):
4.5
Enter the term of your loan (years):
30
Your monthly payment is: $ 1013.37
The slightly difference from your expected output (1013,67) could be due to any sort of rounding error, even a different overload of std::pow choosen by the compiler (since C++11, the integral parameters are promoted to double).
I was doing a program which first takes 2 numbers (with float datatype) from the user and then ask the user about up-to what digit he want's to get the number divided and finally divides it up-to that number and 'cout<<' it. It compiled but din't worked up-to the mark when I calculated 22/7 which is an irrational no. up-to 100 digits it just calculated up-to 30 or 40 digits and then rest of was filled with zeros. Something like this:
3.1428570747375488281250000000000000000000000000000000000000000000000000000000000000000000000000000000
Here is my code:
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main()
{
system("clear");
float y;
int z;
float x;
float a;
cout << "\nHello User\n";
cout << "\nEnter first num to be divided: ";
cin >> x;
cout << "\nCool!! Now enter the 2nd number: \n";
cin >> y;
cout << "\Exelent!! Enter the place upto which u wanna caculate: ";
cin >> z;
a = x / y;
cout << fixed << showpoint;
cout << setprecision(z);
cout << "Calculating......\n" << a << endl;
return 0;
}
Floating point types have certain precision. You don't get exact results when operating on floats (or doubles). Now to get a better precision use double instead of float (See this post for more details).
You could #include <limits>, remove the step that gets the precision from input and change your code to:
std::cout << std::setprecision(std::numeric_limits<float>::max_digits10);
to display the result with maximum precision for the type you use.
I have this code (very basic):
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a = 0.0,
b = 0.0,
c = 0.0;
cout<<"Input a: ";
cin>>a;
cout<<"input b: ";
cin>>b;
cout<<endl;
c = a / b;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
return 0;
}
When I enter two numbers (say, a = 513 and b = 791) I get 0.65. Calculator shows that the correct answer is 0.648. I understand that my code rounds up the last decimal number but this is not what I want.
How can I get it to where it just stays as 0.64 and not 0.65?
If you would like to truncate the value to two decimal places, you can multiply it by 100, truncate to integer, and then divide by 100, like this:
c = a / b;
c = floor(100 * c) / 100;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
Demo on ideone.
You can use trunc to truncate to a certain number of digits:
c = a / b;
// truncate past two decimals:
c = trunc(c * 100) / 100;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
of for a generic function:
int trunc(double val, int digits)
{
double pow10 = pow(10,digits);
return trunc(val * pow10) / pow10;
}
then use
cout << "Result: " << fixed << setprecision(2) << trunc(c,2) << endl;
I'm a beginner in C++ and I came across this code:
#include <iostream>
using namespace std;
int main()
{
const long feet_per_yard = 3;
const long inches_per_foot = 12;
double yards = 0.0; // Length as decimal yards
long yds = 0; // Whole yards
long ft = 0; // Whole feet
long ins = 0; // Whole inches
cout << "Enter a length in yards as a decimal: ";
cin >> yards; // Get the length as yards, feet and inches
yds = static_cast<long>(yards);
ft = static_cast<long>((yards - yds) * feet_per_yard);
ins = static_cast<long>(yards * feet_per_yard * inches_per_foot) % inches_per_foot;
cout<<endl<<yards<<" yards converts to "<< yds <<" yards "<< ft <<" feet "<<ins<<" inches.";
cout << endl;
return 0;
}
It works as you expect but I didn't like all the typecasting business. So I changed this to this:
#include <iostream>
using namespace std;
int main()
{
long feet_per_yard = 3;
long inches_per_foot = 12;
long yards = 0.0;
long yds = 0; // Whole yards
long ft = 0; // Whole feet
long ins = 0; // Whole inches
cout << "Enter a length in yards as a decimal: ";
cin >> yards; // Get the length as yards, feet and inches
yds = yards;
ft = (yards - yds) * feet_per_yard;
ins = (yards * feet_per_yard * inches_per_foot) % inches_per_foot;
cout<<endl<<yards<<" yards converts to "<< yds <<" yards "<< ft <<" feet "<<ins<<" inches.";
cout << endl;
return 0;
}
Which of course does not work as intended because 'long' doesn't have decimal values like 'double' does, right?
But if I change every value to the type 'double', then % does not work with 'double'. Is there a way to make this easier? I heard about fmod() but CodeBlock IDE doesn't seem to recognize fmod()?
Also, I tried 'float' and it seems that % doesn't work with 'float' either. So what are the types of variables that % work with? And where can I find this reference?
Look at std::fmod, which is inherited from C.
Just declare everything as double and you will then not need to cast.
It makes more sense to use double as number of feet is a continuous quantity.
You can also cast in your expression as in:
int daysperweek = 7;
double val = daysperweek * 52.0; // using 52.0 will use implicit conversion