stack around variable is corrupted. C visual studio - c

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.

Related

How do I display comma when typing two variables at the same time?

I am asked to come up with a code register which its input is followed by:
Please enter the amount to be paid: $8.68
Loonies required: 8, balance owing $0.68
Quarters required: 2, balance owing $0.18
The first sentence is completed, but the second isn't, as the comma before the address overlaps with the comma before the word 'balance.'
Is there any way to display comma just as above, and maintain the comma for the address?
#include <stdio.h>
int main(void){
int n_loonies;
int n_quarters;
float remaining;
double amount;
amount = 8.68;
n_loonies = amount / 1;
remaining_loonies = amount -(n_loonies * 1);
n_quarters = amount / 0.25;
remaining_quarters = amount - (n_quarters * 25);
printf("Please enter the amount to be paid:$");
scanf("%lf", &amount);
// printf("loonies required: n_loonies");
// scanf("%d", &n_loonies);
printf("Loonies required:%d,n_loonies, balance owing $%d\n);
return 0;
}
Looks like your print statement is a bit off. It doesn't look like that code would compile, here is an example of how to use print:
int x = 10;
printf("x: %d, x address: %p\n", x, (int *)&x);
There are a number of problems with your code
1) Undeclared variables, e.g. remaining_loonies
2) The scanf is placed after all the calculations so the user input is just ignored
3) The printf is called incorrectly
printf needs a format string and after the format string comes the variables you want to print. All separated by commas.
In the format string the variables are given as % followed by a letter that tells the type of the variable to print, e.g. %d for a signed integer variable, %u for an unsigned integer variable, %f for a float variable and some more...
So to print a single integer do
int my_quaters = 5;
format string
|------------------|
printf("I got %d quaters\n", my_quaters);
^^ ^^
Integer type The variable
When the printf is executed %d will be replaced by the current value of the variable my_quaters - so this will print:
I got 5 quaters
To print two integers do
int my_quaters = 5;
int my_pence = 15;
printf("I got %d quaters and %d pence \n", my_quaters, my_pence);
^^ ^^ ^^ ^^
Integer type Integer type First var Second var
this will print:
I got 5 quaters and 15 pence
So in your case it is more like:
printf("\nLoonies required:%d, balance owing $%.2f\n", n_loonies, remaining_loonies);
note: The format string has a lot more options than I can mention here. Read a good book or man page for that.

what is wrong in this c code? The Answer is always zero?

I am new to c, please help, the answer to this is always zero.why? Instead of converting KM to Metres or centimetres(sorry for typos);
#include <stdio.h>
int main()
{
float Km;
float metres;
float inches;
float centimetres;
printf("Welcome, please enter the distance in Km.\n");
scanf("%f", &Km);
metres = Km * 1000;
centimetres = Km*100000;
inches = Km*25/1000000;
printf("Distance In Metres is:\n");
printf("%f\n", &metres);
printf("Distance in Centimeters is:\n");
printf("%f\n", &centimetres);
printf("Distance in Inches is:\n");
printf("%f\n", &inches);
printf("bye\n");
return 0;
}
printf function writes the value of the variable. The ampersand operator & turns your value into a pointer and that's the error. Instead of printing the actual value of your variables, you are printing the address memory of the pointer.
Read documentation on printf function. More info on & and * here.
You are printing the location of the variables. The calculation is fine, but you're not actually printing the value of the variable. You're printing where it is in memory.
The & operator will give the location of the variable. You can fix your program by removing the &s in the printf statements, i.e. this:
printf("%f\n", &inches);
becomes:
printf("%f\n", inches);
Also, here is a link to a pretty in-depth printf() reference; to learn more about pointers, you can go to this page.

%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.

Math giving incorrect results with value obtained from scanf()

I'm trying to write a function that can, given one, convert between to all four of Kilometers, Miles, Nautical Miles, and Furlongs given one of the four. My Main function looks like:
int main() {
Scale scale; // declared in the header file "length.h"
double value, kilometers, miles, nautical_miles, furlongs;
// prompt user for unit to convert from
printf("\nPlease select which unit you want to convert from:\n");
printf("1. Kilometers\n2. Miles\n3. Nautical Miles\n4. Furlongs\n");
scanf("%d", &scale);
// Get value user wants
printf("Enter value for unit you selected: ");
scanf("%d", &value);
int err = convertLength(&kilometers, &miles, &nautical_miles, &furlongs, scale);
printf("value given was %d\n", value);
kilometers *= value;
//kilometers *= 2;
//kilometers = kilometers * value;
printf("%g Kilos\n%g miles\n%g naut mi\n%g fur", kilometers, miles, nautical_miles, furlongs);
return 0;
}
The conversion is taking place in the file "length.c" and I have only been debugging the kilometers case so far. The Enum declaration for scale is in a header file "length.h".
The issue is that when I multiply kilometers in main() by value, I get an incorrect result (such as 4.940e-324). However, when I only multiply by a constant, like the commented out line //kilometers *= 2; I will get the correct answer (2 in that case). What's going wrong with the variable value that's making it behave in this way?
int convertLength(double *kilometers, double *miles, double *nautical_miles, double *furlongs, Scale scale) {
switch(scale) {
case KILOMETERS:
printf("Kilometers was chosen\n");
*kilometers = 1;
*miles = 1/1.609347219;
*nautical_miles = *miles * 1.15078;
*furlongs = *miles / 8;
break;
Change scanf()'s specifier, for double it is "%lf", not "%d", also
Turn on compiler warnings to avoid this kind of mistake, it should warn you about the incompatibility between the passed pointer and the expected pointer.
Check scanf()'s return value to ensure that your data is find instead of just assuming that it is.

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