I'm just started to learn how to code and decided to try to create a program that would calculate the amount of calories a person burns based on certain values that are asked of them. However, whenever I run it instead of getting the calculated value based on their values I keep getting the value 2686708. I just can't seem to make it work no matter what.
//included libraries
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//constants
#define WALKING_CAL 5
#define EXERCISING_CAL 10
#define EATING_CAL 40
#define DRINKING_CAL 20
#define CALORIES_PER_POUND 3500*/
//main function
int main() {
int current_weight, goal_weight;
int walking, exercise, drinking, eating;
int total_walking, total_exercising, total_eating, total_drinking;
int calories_burned, calories_gained;
printf("What is your current weight?\n");
scanf("%d", ¤t_weight);
printf("\nWhat is your goal weight?\n");
scanf("%d", &goal_weight);
total_walking = WALKING_CAL * walking;
total_exercising = EXERCISING_CAL * exercise;
total_eating = EATING_CAL * eating;
total_drinking = DRINKING_CAL * drinking;
calories_burned = (total_walking + total_exercising)- (total_eating + total_drinking);
if (goal_weight > current_weight){
printf("\nHow many minutes do you walk per day?\n");
scanf("%d", &walking);
printf("\nHow many minutes do you exercise per day?\n");
scanf("%d", &exercise);
printf("\nHow many minutes do you drink per day?\n");
scanf("%d", &drinking);
printf("\nHow many minutes do you eat per day?\n");
scanf("%d", &eating);
printf("You gain %d calories per day.", &calories_burned);
}
return 0;
}
This:
printf("You gain %d calories per day.", &calories_burned);
prints the address of the variable, not the variable's value (as an int, which in turn is undefined behavior but seems to not blow up for you at least).
It should be:
printf("You gain %d calories per day.", calories_burned);
Drop the &.
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...
int main(){
int TIMES_TAKEN_JUICE, COUNTER =0, amount_of_Juice, TOTAL_JUICE_TAKEN;
float COST_OF_JUICE_TAKEN, JUICE_AMOUNT_TAKEN, COST_OF_JUICE, JUICE_COST_PER_OZ;
printf("What is the weight (in oz.) of the original container of OJ?\n");
scanf("%d", &amount_of_Juice);
printf("What is the cost of the original container of OJ in dollars?\n");
scanf("%f", &COST_OF_JUICE);
JUICE_COST_PER_OZ = COST_OF_JUICE / (float) amount_of_Juice;
printf("%f", &JUICE_COST_PER_OZ);
printf("How many times did your roommate take your juice?\n");
scanf("%d", &TIMES_TAKEN_JUICE);
while(COUNTER < TIMES_TAKEN_JUICE){
printf("How much juice did your roommate take this time (in oz.)?\n");
scanf("%d", &JUICE_AMOUNT_TAKEN);
COUNTER++;
TOTAL_JUICE_TAKEN += JUICE_AMOUNT_TAKEN;
COST_OF_JUICE_TAKEN = TOTAL_JUICE_TAKEN * JUICE_COST_PER_OZ;
if (COST_OF_JUICE_TAKEN >= 10.00)
{
printf("Your roommate owes you $10.00\n");
}
}
return 0;
}
I have no clue why the JUICE_COST_PER_OZ variable is not working. I have tried every possible combination I can think of.
scanf needs & before variable names because it modifies them. printf doesn't because it only reads them. Make the printout read:
printf("%f", JUICE_COST_PER_OZ);
Style comment: I recommend you lowercase all the variables. Uppercase is normally only used for constants, not for regular variables.
I am not allowed to use arrays nor anything else I have not yet studied in the course, e.g: pointers, dynamic memory allocations, etc. What I have studied so far is: Functions and loops. I need to list all of the course codes, days, and times for as many courses as the user has specified in the first scanf_s call. I have no idea how to proceed without using arrays. Any hints/help would be appreciated.
printf("Please enter the number of courses you'd like to take: ");
int numOfCourses;
scanf_s("%d", &numOfCourses);
int courseCode;
int courseDay;
int courseTime;
int i = 0;
while (i < numOfCourses) {
printf("Please enter the code of the course: ");
scanf_s("%d", &courseCode);
printf("Please enter the day of the course: ");
scanf_s("%d", &courseDay);
printf("Please enter the time of the course: ");
scanf_s("%d", &courseTime);
i++;
}
Suggest:
1) create a struct that holds all the info for an individual student
2) create a file, perhaps in the local directory or in /tmp
3) for each student, after collecting the information, write the struct to the file
--or--
given the MAX number of courses that a student can take, then code similar to:
int course1day;
int course1time;
int course1code;
(repeat for MAX number of courses, increment the digit for each course)
a consideration is: what will the code be doing with this information after it is collected?
Assuming that courseCode is a single digit number representing the course you could do something like this:
printf("Please enter the number of courses you'd like to take: ");
int numOfCourses;
scanf_s("%d", &numOfCourses);
int courseCode;
int courseDay;
int courseTime;
// unsigned long to have the most possible space
unsigned long courseCodeArray = 0;
unsigned long courseDayArray = 0;
unsigned long courseTimeArray = 0;
int i = 0;
while (i < numOfCourses) {
// single digit code
printf("Please enter the code of the course: ");
scanf_s("%d", &courseCode);
// 1 = Monday, 2 = Tuesday, 3 = Wednesday , etc.
printf("Please enter the day of the course: ");
scanf_s("%d", &courseDay);
// 1 = 8:00, 2 = 10:00, 3 = 12:00, etc.
printf("Please enter the time of the course: ");
scanf_s("%d", &courseTime);
courseCodeArray += courseCode;
courseDayArray += courseDay;
courseTimeArray += courseTime;
courseCodeArray = courseCodeArray * 10;
courseDayArray = courseDayArray * 10;
courseTimeArray = courseTimeArray * 10;
i++;
}
This way you would have an "array" made with a single int that could work as long as the code of the course is an integer between 1 and 9.
E.G. the numbers: 435 , 132 and 431
Would mean: 4-1-4 Course 4 Monday at 14:00 , 3-3-3 Course 3 Wednesday at 12:00 and 5-2-1 Course 5 Tuesday at 8:00 respectively.
Of course you then need to write some checks to ensure that the user will enter only valid numbers, that you don't go past the maximum unsigned long value and make better design choices but i think this is what your professor meant by
Make your code robust and easy to read
So I won't do absolutely everything for you ;)
With this you essentially store multiple values in a single unsigned long or int as long as you know how to "decode" the single digits to their representation. Just divide the arrays by 10 to remove the last 0 and then read digit by digit of the resulting "array" numbers and convert them back.
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 :)