i wanted to ask is my coding have something missing or i did wrong? I was doing function to calculate the employee salary. it can compile and run, but not showing the output that should produce.
I'm trying to get the out like this: (example the value of the output)
Please enter your salary: 1200
Please enter the persentage of epf deduction:11
Your epf deduction is $132.00
Your bonus (half of salary) is $600.00
Your total pay is $1200.00-$132.00+$6000.00=$1668.00
My coding is like this:
void BasicSalary(); //Ask user to enter basic salary.
void EPF(double); //To calculate the amount of employees evident fund (EPF) deduction from basic salary.
void CalculateBonus(double); //To calculate the amount of bonus. Assume bonus is half of basic salary.
double DisplayTotalPay(double,double); //To calculate the total pay after EPF deduction and bonus reward.
double salary,epf,totalepf,totalbonus;
int main()
{
void BasicSalary();
void EPF(double);
printf("\nYour EPF deduction is $%f ",totalepf);
printf("\nYour bonus (half of salary) is $%f ");
void CalculateBonus(double);
double DisplayTotalPay(double,double);
}
void BasicSalary()
{
printf("\nPlease enter your salary: ");
scanf("%f",&salary);
}
void EPF(double)
{
printf("\n\nPlease enter the percentage of EPF deduction: ");
scanf("%f",epf);
totalepf= ( epf / 100 ) * salary;
}
void CalculateBonus(double)
{
totalbonus = salary / 2;
}
double DisplayTotalPay(double,double)
{
printf("\nYour total pay is $%f - $%f + $%f = $%f ", salary, totalepf, totalbonus, salary-totalepf+totalbonus);
}
you have kept everything in your main under comment. How it will work .?
Also your functions argument variables are not named. Since all your variable are global, you don't require any argument. Better remove those data type declaration.
Another point is, use "%lf" with Double when scanning. "%f" is for float.
Related
Good day, I am practicing about Arithmetic and started to experiment a bit and got confused. How can I total the liter, refueled, and tendered?
#include <stdio.h>
int main()
{
int liter, refueled, tendered, changed;
printf("Enter the price of the fuel per liter: ");
scanf("%f",&liter);
printf("Enter the number of liters the customer wants refueled: ");
scanf("%f",&refueled);
printf("Enter the amount tendered: ");
scanf("%f",&tendered);
printf("your change is %.2f pesos. Thank you and come again!", changed = liter * refueled - tendered);
return 0;
}
It seems like float is more appropriate for all your variables (liter, refueled, tendered, changed). There's no reason to allow only integer amounts of fuel etc. You also scanfed them using "%f" which is used for floats.
It's better to assign changed in a separate line, or alternatively get rid of it altogether and simply put the mathematical expression in the printf call.
You inverted the value of changed. Should be tendered - liter * refueled.
Better version:
#include <stdio.h>
int error_handler(/*error params*/)
{
int errCode{ 1 };
// Error handling based on the params, set errCode ...
return errCode;
}
float get_change(float liter, float refueled, float tendered)
{
return tendered - liter * refueled;
}
int main()
{
float liter{ 0 }, refueled{ 0 }, tendered{ 0 };
printf("Enter the price of the fuel per liter: ");
if (scanf("%f", &liter) != 1) {
return error_handler(/*error params*/);
}
printf("Enter the number of liters the customer wants refueled: ");
if (scanf("%f", &refueled) != 1) {
return error_handler(/*error params*/);
}
printf("Enter the amount tendered: ");
if (scanf("%f", &tendered) != 1) {
return error_handler(/*error params*/);
}
printf("your change is %.2f pesos. Thank you and come again!\n", get_change(liter, refueled, tendered));
return 0;
}
Update:
Following the comments below I updated my solution with:
Skeleton for error handling for scanf.
A separate function for the change calculation. In this case it seems a bit contrived, but it's correct from a methodical software engineering point of view (imagine this calculation getting a lot more complex in some real life scenario). Note: you can further apply this principle and extract for example the code for getting input from the user to a separate function. In my code above I decided it is enough to demonstrate it with get_change and error_handler.
Your scanning attempts, e.g. scanf("%f",&liter); uses the format specifier for float, but gives the address of an integer.
That causes undefined behaviour, which means "do not do this" for practicals (otherwise look up the term, or for fun "nasal demons").
The simplest fix (assuming you input integer values) is to switch to "%d".
If you instead switch to using float for the variable (probably necessary), you should know, for the cases of currency (e.g. tendered), that a very recommended best practice is to then convert to an integer variable which counts the smallest denomination, e.g. cents.
I took the answer of wohlstad, which was nearly perfect and added a function for your calculation...
#include <stdio.h>
fload calculation(fload tendered, fload liter, fload refueled);
int main()
{
float liter, refueled, tendered, changed;
printf("Enter the price of the fuel per liter: ");
scanf("%f", &liter);
printf("Enter the number of liters the customer wants refueled: ");
scanf("%f", &refueled);
printf("Enter the amount tendered: ");
scanf("%f", &tendered);
changed = calculation(tendered, liter, refueled);
printf("your change is %.2f pesos. Thank you and come again!", changed);
return 0;
}
fload calculation(fload tendered, fload liter, fload refueled){
fload calcVal = tendered - liter * refueled;
return calcVal;
}
Now you can edit your calculation like you need it, adding more or less things etc...
There's some problem with the 'calculate the total' part but I'm unsure what it is. Everything else runs fine besides it.. I get the "result_pointer != nullptr" error everytime.
void CalculateTotal(double pricePerGallon, double* totalPtr)
//input price per gallon
//declare, ask and get the number of gallons
//calculate the total
//input/output parameter for the total
{
//declare, ask and get the number of gallons
int numGal = 0;
double tot;
printf("Enter the number of gallons requested: ");
scanf("%d", numGal);
//calculate the total
tot = numGal * pricePerGallon;
*totalPtr = tot;
printf("Your total is %f.", totalPtr);
}
unsure if it matters, but I called it in another function definition like so:
CalculateTotal(itemNumber, &total);
(I'm just learning programming for my class, so the simpler the explanation, the better. This is not C++ btw, just C.)
scanf should get a pointer, so your call to the function is wrong and should be as follows:
scanf("%d", &numGal);
You also have a bug in your call to printf, which should be as follows:
printf("Your total is %f.", *totalPtr);
You need to use the indirection operator due to the fact that totalPtr is a pointer.
Im making a shipping calculator that ask how many pounds your item weighs. If it weighs less than 50 pounds the charge is 6.00. If it weighs 50 pounds but less than 100 pounds the charge is 10.50. The shipping charge also doubles for every 1000 miles. Im having a problem figuring out how to make the calculator double if user inputs over 1000 miles.
int main()
{
double weight, distance, charge;
printf("Enter your package weight: \n");
scanf("%lf", &weight);
printf("How far are you sending the package? \n");
scanf("%1lf", &distance);
if(weight <= 50)
charge = 6;
else
if(weight <= 100)
charge = 10.50;
printf("Shipping charge: %.2lf\n", charge);
}
When I run the program I dont get the correct shipping charge.
Maybe you should printf the charge instead of the weight?
In your code you are outputting weight in the end and not the charge, the one that was actually mutated.
Need some help with calculating the fixed monthly payment (P) required to fully amortize a loan of L dollars over a term of n months at a monthly interest rate of i. The given formula is: P = L[i(1 + i)n]/[(1 + i)n - 1]. I wrote a code but it didn't calculate Payment. I'm wondering if it is because I use double type together with int (for number of months) or the problem with formula?! Please help.
#include<stdio.h>
#include <math.h>
double calculatePayments(double rate, double loan, int payments);
int main() {
double principal, i, monthlyP;
int month;
printf ("Enter the principal amount: ");
scanf ("%f", &principal);
printf ("Enter the interest amount: ");
scanf ("%f", &i);
printf ("Enter the term in months: ");
scanf ("%d", &month);
monthlyP = calculatePayments (i, principal, month);
printf ("The monthly payment amount is %.2f: ", monthlyP);
return 0;
}
double calculatePayments(double rate, double loan, int payments) {
double mPayments;
mPayments = loan*(rate*(1 + rate)*payments)/((1 + rate)*payments - 1);
return mPayments;
}
Your scanf() requests %f format for a double; it should be %lf.
In addition to the need to fix the input (%lf instead of %f for doubles), I think your payment formula is wrong: since the future value of money grows exponentially, the formula should feature raising numbers to a certain power, which it does not.
The correct formula looks as follows (from here):
Since the loan needs to be paid off completely, FV is equal to zero.
Since pow(i+1, n) is used twice, it's a good idea to compute it once, and use the resultant variable in two places. The final version of this computation looks like this:
double calculatePayments(double rate, double loan, int payments) {
double mul = pow(1+rate, payments);
return (loan * mul * rate) / (mul - 1);
}
Demo on ideone computes the payment on $100,000 at 0.004% per month for 30 years at $524.67, which is the same value that excel's PMT function returns.
Note : When you enter the rate of 5.6% in your formula and in another calculator, don't forget that your formula takes the rate per month, not per year. Therefore, the rate that you plug into outside calculators must be 12 times what you enter into your calculator (for 5.6% annually you should enter 0.00466666
One of the first rules of debugging is to make sure you print the inputs to ensure that the program got the values you expected. It didn't, because you wrote:
scanf ("%f", &principal);
Since principal is a double, the format needs to be "%lf". Repeat for the interest rate. You should also check that the inputs succeeded:
if (scanf("%lf", &principal) != 1)
{
fprintf(stderr, "Failed to read principal\n");
return(1);
}
If you'd printed out the input values, you'd have known what was wrong immediately.
Read what dasblinkenlight said.
Also,
Fix your declarations and the variables you are using scanf() for.
principal should be loan. month should be payments.
i is okay. You need to calculate the monthly decimal number of the percentage given.
For instance,
interest = (i/100) /12;
Do that before your function call. Then just basically use dasblinkenlight's function at the bottom of your main.
hope you score a "10" ;)
//A program that calculates the amount of money in a bank account after n years
#include <stdio.h>
double bank(double money, double apy, int years);
int main() {
double money1, apy1;
int years1;
printf("How much money is currently in your bank account? ");
scanf("%d", &money1);
printf("How many years will this money stay in your account? ");
scanf("%d",&years1);
printf("What is your APY? ");
scanf("%d", &apy1);
int bank1 = bank(money1, apy1, years1);
printf("Your grand total after %d will be $%d \n", years1, bank1);
system ("PAUSE");
return 0;
}
double bank(double money, double apy, int years) {
if(years <= 0)
return money;
else
return bank(money*apy, apy, years-1);
}
Change:
scanf("%d", &money1);
to
scanf("%lf", &money1);
and change:
scanf("%d", &apy1);
to:
scanf("%lf", &apy1);
And while you're at it you might want to add some printfs to help with debugging (assuming you don't have a source level debugger.)
This:
return bank(money*apy, apy, years-1);
should probably be
return bank(money*(1+apy), apy, years-1);
since the interest you earn should be added to the existing amount. Otherwise your total amount would be reducing each year.
Another one is :
double bank(double money, double apy, int years);
Returns a double, but
int bank1 = bank(money1, apy1, years1);
You place the result in an int.
You should never use floating point in financial calculations.
Floating point is inherently uncapable of representing 10-base values precisely, which means that you will suffer from rounding errors and unequalities, which is unacceptable in finances (among others).
This has been discussed in detail many times on SO. The issue is not language specific.
I think you should call you function in the following way:
int bank1 = bank(money1, 1+apy1/100., years1);
Otherwise you'll have a LOT of money :)