#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).
Related
I', trying to make a simple BMI calculator using C++. When I input my personal height and weight, I get the correct result but I can't round the number to the nearest whole number. I looked up some videos and some articles and many of them suggested using the "round()" function. I tried that and the result I got was 0!
All feedback helps. Thanks!
#include <iostream>
#include <cmath>
using namespace std;
float Calculate(float kilo, float centimeter)
{
float meter = centimeter * 100;
return kilo / (meter * meter);
}
int main()
{
float kilo, centimeter;
float bmi;
cout << "BMI calculator." << endl;
cout << "Please enter your weight in kilograms. ";
cin >> kilo;
cout <<"Please enter your height in centimeters. ";
cin >> centimeter;
bmi = Calculate(kilo, centimeter);
cout << round(bmi) << endl;
return 0;
}
Your formula for calculating BMI is wrong just change the line float meter = centimeter/100;.
because according to your formula any number multiplied by 100 and then squared becomes so big that you get very small floating point number after the division with weight that is eventually rounded that's why you always get 0 in output.
The following snippets are the header file and the actual main() function. I am using Visual Studio 2017 with Windows 10.
.h
#ifndef SALES_DATA_H
#define SALES_DATA_H
#include <iostream>
using namespace std;
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
};
#endif
.cpp
#include <iostream>
#include "Sales_data.h"
using namespace std;
int main()
{
Sales_data item1;
cout << "Enter rate and amount" << endl;
cin >> item1.rate >> item1.amount;
cout << item1.price << endl;
cin.get();
cin.get();
return 0;
}
It keeps showing this as the output: "687194768".
I also tried initializing the variables but it does not seem to work.
What you probably want is:
struct Sales_data
{
int amount = 0;
int rate = 0;
int price() const { return amount * rate; }
};
And then
std::in >> item1.rate >> item1.amount;
std::cout << item1.price() << std::endl;
Price here is being calculated only at initialisation time to get its initial value, however since amount and rate have not been initialised yet, the result is undefined.
It is not a function.
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
};
You most likely wanted a function, e.g.:
struct Sales_data
{
int amount;
int rate;
int calcPrice()
{
return = amount * rate;
}
};
std::cout << item1.calcPrice() << std::endl;
Or you would have to refactor to initialise amount and rate to make use of such syntax, e.g. with a constructor.
struct Sales_data
{
int amount;
int rate;
int price = amount * rate;
Sales_data(int amount, int rate) : amount(amount), rate(rate) {}
};
Sales_data x(10, 5);
//x.price == 50
the reason the code is printing that is because you are calculating that price with uninitialized variables...
define a function in the struct and call it after the input is given
void calculatePrice() {
price = amount * rate;
}
cin >> item1.rate >> item1.amount;
item1.calculatePrice();
cout << item1.price << endl;
As others have commented, your definition for Sales_data uses amount or rate before they were ever initialised. This is undefined behaviour, and your compiler is more or less free to do whatever it pleases with this.
Many compilers will initialise variables with some sort of recognisable guard value (a popular choice is 0xDEADBEEF) as a way to make it quite obvious when a value is uninitialised when looking at it with a debugger. In this case, it looks like your compiler uses 0xCCCCCCCC as that guard value:
(lldb) p (int) 0xcccccccc * (int) 0xcccccccc
(int) $2 = 687194768
c++ and I'm trying to figure out why my code returns 0's from a few statements after the user inputs some float numbers. I'm not sure why. Maybe someone can help:
This is what I get after running my method and answering the questions before it:
The number of gallons of paint required is: 0 gallons
Hours of labor that is required: 0 hours
.
Also ignore the () around my # in the beginning. I will put periods between lines to make it look neater on this website.
/**
* A painting company has determined that for every 160 square feet of wall
space, one gallon of paint and 3 hours of labor are required.
* The company charges the $28.00 per hour for labor.
* Design a modular program that allows the user to enter the number of rooms
that are to be painted,
* the approximate square feet of wall space in each room (may differ from room
to room), and the price per gallon of paint.
* It should then create a report that includes a fancy company header and
displays the following information:
* The number of gallons of paint required: (Rounded up to the next full
gallon)
* The hours of labor required:
* The cost of the paint:
* The labor charges:
* Total cost of the paint job:
* Requirements:
* Input validation: The program should not accept a value less than 1 or
more than 12 for the number of rooms
* Should not accept a value less than 100 for the square
footage of a room.
* Should not accept a value less than $10.00 or more
than $25.00 for the price of a gallon of paint
*
* Lets do this...
*/
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
float priceOfGallon(float);
float numberOfGallons(float, float);
float totalWallArea(float, float, float);
float laborHours(float, float);
void fancyCompanyHeader();
int main() {
float area;
float totalArea;
float min_labor = 3;
float number_of_rooms;
float number_of_gallons;
float price_of_gallon;
totalWallArea(area, totalArea, number_of_rooms);
priceOfGallon(price_of_gallon);
numberOfGallons(number_of_gallons, totalArea);
laborHours(number_of_gallons, min_labor);
fancyCompanyHeader();
return 0;
}
// function that gets the number of gallons needed for the total area
float numberOfGallons(float number_of_gallons, float totalArea) {
number_of_gallons = (totalArea / 160.0);
std::cout << "The number of gallons of paint required is: " <<
number_of_gallons << " gallons" << std::endl;
}
float priceOfGallon(float price_of_gallon){
std::cout << "Please enter the price per gallon: " << std::endl;
cin >> price_of_gallon;
while(price_of_gallon < 10.00 || price_of_gallon > 25.00) {
std::cout << "The price should be between $10.00 and $25.00. Please try again: " << std::endl;
cin >> price_of_gallon;
}
}
float totalWallArea(float area, float totalArea, float number_of_rooms) {
std::cout << "Please enter the number of rooms that needs to be painted:" <<
std::endl;
std::cin >> number_of_rooms;
while(number_of_rooms < 1)
{
cout << "Number of rooms must be at least one. Please try again: " <<
std::endl;
cin >> number_of_rooms;
}
for(float i = 1; i <= number_of_rooms; i++)
{
cout << "Please enter the square feet of wall space needed for Room " <<
i << std::endl;
cin >> area;
while(area < 100)
{
std::cout << "The area should be 100 or greater. Please try again: "
<< std::endl;
cin >> area;
}
totalArea += area;
}
}
// I will finish this method later
float laborHours(float number_of_gallons, float min_labor) {
min_labor = number_of_gallons * 28.00;
std::cout << "Hours of labor that is required: " << min_labor << " hours "
<< std::endl;
return min_labor;
}
You need to make all of those variables you are modifying global (Declared outside of int main()). In C++, when you give a function a variable, it will just copy the contents of the variable into the function's variables: the original variable passed in remains constant. Thus, your uninitialized floats default to 0 and are not changed by any of the functions, so when they are given to the laborHours function or numberOfHours function, 0s are passed into each.
Example with much better practices than in your code (it's ok, everyone starts by writing atrocious code) :
#include <iostream>
int walls,rooms,total_walls; //It only makes sense if all of these are integers.
//These are global declarations, they can be modified by any function in the program
void input_walls() {
/* Functions are notated as so in C++:
{return type} {function_name}({input},{input},...)
It's pointless to annotate functions that don't return anything
with a declaration of a float return type (they'll just return 0 */
std::cin >> walls;
while(walls < 0) {
std::cout << "Please input a positive amount of walls per room.";
std::cin >> walls;
}
}
void input_rooms() {
std::cin >> rooms;
while(rooms < 0) {
std::cout << "Please input a positive amount of rooms";
std::cin >> rooms;
}
}
void calculate_result() {
total_walls = walls*rooms;
}
void output_result() {
std::cout << "I'll need to paint " << total_walls << " walls!" << std::endl;
}
int main() {
input_walls();
input_rooms();
calculate_result();
output_result();
}
This still isn't the best way to write this, but it's still the exact same thing you were trying to do. Now try rewriting what you were trying to do in this style!
TLDR/Quick fix: Make the variable definitions global, cut out the arguments from the functions.
Recently I've started doing Code Chef challenges to practice programming in C and C++ when I came across the ATM challenge. The challenge (which I expected to be relatively easy) was to create a program that withdraws money from a bank account if the withdrawal amount is a multiple of 5 and if the withdraw > balance. If the transaction is accepted it also charges a fee of 0.5, else it just reprints the bank data.
The link to the challenge is here:
https://www.codechef.com/problems/HS08TEST
The program runs perfectly fine for me on my computer but for some reason it is wrong.
Here is my program:
#include <iostream>
#include <cstdio>
#include <iomanip>
using std::cout; using std::cin; using std::endl;
class Bank_data {
private:
double balance;
public:
void withdraw (int amount) {
if (amount > balance - 0.5 || amount % 5 != 0)
printf("%.2f\n", balance);
else
printf("%.2f\n", balance - amount - 0.5);
}
void setBalance (int amount) {
balance = amount;
}
};
int main () {
Bank_data bd;
int withdraw, init_val;
cin >> std::fixed;
cin >> std::setprecision(2) >> withdraw >> init_val;
bd.setBalance (init_val);
bd.withdraw (withdraw);
return 0;
}
Sample io:
I: 5 500
O1: 494.50
I2: 600 500
O2: 500.00
I3: 4 500
O3: 500.00
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.