What is wrong with my Cost per oz Calculations - c

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.

Related

How to get the total?

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

I need to create table using C that takes input from user without using Arrays, Dynamic Arrays, or Dynamic Memory Allocation

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.

averaging while looping, the sum won't clear and thus keeps adding numbers from previous loop entry

#include <stdio.h>
int main () {
int days, flights, t, b;
float length, mean, sum;
printf("How many days has your dragon been practicing?\n");
scanf("%d", &days);
for(t=1; t<=days; t++) {
printf("How many flights were completed in day #%d?\n", t);
scanf("%d", &flights);
for(b=1; b<=flights; b++) {
printf("How long was flight #%d?\n", b);
scanf("%f", &length);
sum+=length;
}
mean = sum/flights;
printf("Day #%d: The average distance is %.3f.\n", t, mean);
}
}
the sum used to calculate the mean is supposed to be only the number from one iteration of the loop added together. instead the sum used numbers from the new iteration and old iteration added together.
If I understood your problem correctly, after the last printf() statement, you should reset sum to 0, like sum = 0;.
That said, the major issue in your code is that, you're using sum (an automatic storage local variable) while uninitialized. You should be initializing sum to some value (0, maybe) before making use (sum+=) of it. Otherwise, it it invokes undefined behavior.
To quote C11 standard, chapter ยง6.7.9
If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. [...]
sum won't clear because you don't clear it ! The point of writing code is to make your dumb machine(yeah dumb!) know when it's got to do what!
So immediately after
for(t=1;t<=days;t++)
{
Add this:
sum=0;
This will ensure that your sum value is reset every day your dragon takes a flight! Otherwise C will use some random garbage value as your sum and you would receive weird answers!
Some suggestions:
1) If you call scanf() just after you call printf(), there is no reason to use '\n' inside that printf at the end.
2) Always check scanf() for errors or your code is useless if errors occurs.
Now about your code:
When you use something like x+=y this means x = x + y.
So, in your case sum+=length means sum=sum+length. Do you know the value of sum? Yes is a garbage value.
About this line mean = sum/flights;, what is mean, sum and what is flights? Yes, first are float but second is int.
Now putting all together:
#include <stdio.h>
int main (void){
int days, flights, t, b;
float length, mean, sum=0;
printf("How many days has your dragon been practicing?: ");
if((scanf("%d", &days)) != 1){
printf("Error\n");
}
for(t=1; t<=days; t++) {
printf("How many flights were completed in day #%d?: ", t);
if((scanf("%d", &flights)) != 1){
printf("Error\n");
}
for(b=1; b<=flights; b++) {
printf("How long was flight #%d?\n", b);
if((scanf("%f", &length)) != 1){
printf("Error\n");
}
sum+=length;
}
mean = sum/(float)flights;
printf("Day #%d: The average distance is %.3f.\n", t, mean);
}
return 0;
}

C - Output value not calculating correctly

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", &current_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 &.

What is wrong with the following code?

//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 :)

Resources