while loop in C programing - c

Write a program that contains the loop
while (scanf("%1f", &salary) == 1) {...}
within the body of the loop compute a 17% federal withholding tax and a 3% state withholding tax and print these values along with the corresponding salary. Accumulate the sums of all salaries and taxes printed. Print these sums after the program exits the while loop.
My current code:
float salary, federal_tax, state_tax, salary_after_tax, salary_sum, tax_sum, salary_after_tax_sum;
printf("Enter Salary: $");
while (scanf("%lf", &salary) == 1)
{
salary_sum = salary;
federal_tax = salary*(.17);
state_tax = salary*(.03);
tax_sum = federal_tax + state_tax;
salary_after_tax = salary - federal_tax - state_tax;
salary_after_tax_sum = salary_after_tax;
printf("Salary before tax = %lf", salary);
printf("Federal tax = %lf", federal_tax);
printf("State tax = %lf", state_tax);
printf("Salary after tax = %lf\n", salary_after_tax);
break;
}
printf("total salary before tax = %lf", salary_sum);
printf("total tax = %lf", tax_sum);
printf("total salary after tax = %lf\n", salary_after_tax_sum);
system ("pause");
return 0;
}
For some reason it doesn't work. Any help would be appreciated.

Your scanf specifier is %lf (your problem statement says %1f instead, is that intentional?) and yet you're storing into a float. My scanf(3) says %lf specifies a double.
Incidentally, float has much less precision than many programmers may expect, just about seven digits, so using double instead is probably a good idea for salaries.

You should assign your ..._sum variable to 0 outside the loop, and increment them with += in the loop; what you're doing now instead is reassigning them every time through the loop, and that isn't summing!-)

You lied to the compiler and it got its revenge: the %lf format needs to go with a pointer-to-double, while you provide only a pointer-to-float. This means undefined behavior in C lingo (anything may happen).
Fix your float declarations by turning them into doubles.

Related

"debug assertion failed! expression: result_pointer != nullptr" problem

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.

C Program gets stuck in an infinite loop

The problem I've been having is that my code will get stuck either in an infinite loop or will have a stack overflow problem and begin producing negative numbers during calculations.
I am aware that this issue is coming from my while loop and also think the issue probably lies with the formula I am using being the line i = (r / 12)*(b - p + temp);.
However I am unsure of how to fix this. My formula is trying to calculate the interest paid on a fixed interest loan for each month over 12 months and print that to the screen with the remaining balance. This is supposed to continue until the balance reaches 0.
#include <stdio.h>
// main function
int main()
{
// variable declarations
float r = 0.22; // interest rate
float b = 5000.0; // amount borrowed
float p; // payment amount
int m = 1;
float temp, ti = 0;
float i;
// Take in data from user
printf("Please enter the amount you wish to pay monthly: \n");
scanf("%f", &p);
printf("\n");
//display interest rate, initial balance, monthly payment
printf("r = %.2f\nb = %.1f\np = %.1f \n\n", r, b, p);
// Month by month table showing month interest due/paid and remaining balance
i = (r / 12) * b;
temp = i;
printf("%d %.2f %.2f\n", m,i,b);
m++;
while (i > 0) {
i = (r / 12) * (b - p + temp);
b = (b - p + temp);
ti += temp;
temp = i;
printf("%d %.2f %.2f\n",m, i, b);
m++;
}
printf("\n");
printf("total interest paid: %.2f\n", ti);
return 0;
}
Well, if I'm doing the math correctly it looks like if you enter a value less than 91.67 for P you are going to get stuck in an infinite loop because the monthly payments are less than the interest accusing on the debt; so you might want to add a check for that.
As an aside if you named your variables as Interest, Base, etc. you wouldn't need the comments and the code would be easier to read.
Also since you are printing out the payment info until balance is zero you should loop while b > 0.
The program works as expected.
The only problem is, if your monthly payment are less
than the interest rate - then the amount you need to pay back
grows exponentially and the program never stops.
Enter any number >= 92 and it seems to work.
Is 22% p.a. interest rate correctly?
I don't see this generating an infinite loop but it would become a problem if your repayment is higher than the matured interest, which with your starting parameter it means anything below 91.67.
You may have a wrong end condition so there is always a negative line printed, though.

%lf' expects argument of type 'double', but argument 2 has type 'double *'

Why am I getting this warning while trying to compile my program?
%lf' expects argument of type 'double', but argument 2 has type 'double *'
I'm using CodeBlocks IDE, But these lines give a huge number:
double calculate1 = mealPrice * (double)(percentage)/100;
printf("The tip that you should leave is %lf \n", &calculate1);
I'm new to C programming and still learning stuff.
// CS 262, Lab Section <208>
// Lab 2
#include <stdio.h>
#include <stdlib.h>
int main(){
printf("Enter the price of the meal: \n");
double mealPrice = 0;
scanf("%lf\n", &mealPrice);
printf("Now enter the tip percentage: \n");
int percentage = 0;
scanf("%d\n", &percentage);
//Calculates tip amount in double, int, and float types
double calculate1 = mealPrice * (double)(percentage)/100;
printf("The tip that you should leave is %lf \n", &calculate1);
int calculate2 = (int)mealPrice * (int)(percentage/100);
printf("The tip that you should leave is %d\n", &calculate2);
float calculate3 = (float)mealPrice * (float)(percentage/100);
printf("The tip that you should leave is &f\n", &calculate3);
//Add tip to meal price
double total = calculate1 + mealPrice;
printf("The total price including tips is %lf\n", total);
printf("The meal cost is %f\nThe tip percentage is %d\nThe tip amount is%lf\nThe total cost is %lf\n", &mealPrice, &percentage, &calculate1, &total);
return 0;
}
The problem is that you should not use pointers with printf (unless you are using pointer format specifiers). You generally pass things by pointer to scanf (because it needs to change them) and by value to printf (because it's not supposed to change them). That's why you are getting huge numbers.
It should look like:
printf("The tip that you should leave is %lf \n", calculate1);
and
scanf("%lf\n", &mealPrice);
not
printf("The tip that you should leave is %lf \n", &calculate1);
or
scanf("%lf\n", mealPrice);
Also in the future, don't show us compiler warnings unless they are specifically connected to the code that you posted, or you are going to get confused responses.

stack around variable is corrupted. C visual studio

I am making a program to convert weight and height from metric to US and vice versa. I did the height part successfully, but the part with the weight is giving me a runtime error that stack around variable was corrupted.
I know that happens with arrays because pretty much thats all I get when I google the issue, but this is happening with a regular integer variable in 2 different functions.
This is the function that calls other functions to convert weight, one is for input, one is to convert and one is for output:
void weight_to_metric(void){
int kilograms, pounds;
double grams, ounces;
int * pkilograms= &kilograms, *ppounds=&pounds;
double * pgrams=&grams, *pounces=&ounces;
input_us_weight(ppounds, pounces);
weight_us_to_metric(ppounds, pounces, pkilograms, pgrams);
output_metric_weight(pkilograms, pgrams);
}
this is the function that inputs
void input_us_weight(int* feet, double * inches){
printf("enter the number of pounds you want to convert: ");
scanf(" %lf", feet, "\n");
printf("enter the number of ounces you want to convert: ");
scanf(" %lf", inches, "\n");
}
this is the function that converts
void weight_us_to_metric(int* pounds, double* ounces, int* kilograms, double * grams){
double temp_kilograms;
*kilograms = *pounds / 2.2046 + ((*ounces / 16) / 2.2046);
temp_kilograms = *pounds / 2.2046 + ((*ounces / 16) / 2.2046);
*ounces = ((temp_kilograms - *kilograms) *2.2046)*16;
*grams = ((*ounces / 16.0)/2.2046) * 1000;
}
The output function doesn't even deal with the variable that corrupts. The variable that corrupts is pounds. The integer pounds declared in the initial variable.
How do i fix this?
You are using wrong format specifiers in one of your scanfs. Use %d when scanning an int and %lf when scanning a double. Change
scanf(" %lf", feet, "\n");
to
scanf("%d", feet);
Also, remove the third argument("\n") that you pass to the scanfs. It makes no sense.

Monthly payments C program

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" ;)

Resources