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...
Related
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 want to be able to take someones amount owed as the price, and then do some math from the amount received and print my result.
Below is the code I came up with. However, my program does not run after showing the amount tendered.
Any thoughts?
Note, it is my first time coding in C, and I'm from Java..
#include <stdio.h>
int main (void) {
double tendered;
double changeDue;
double price;
int hundred=0;
int twenty=0;
int ten=0;
int five=0;
int toonoe=0;
int loonie=0;
int quarter=0;
int dime=0;
int nickle=0;
int penny=0;
/* Statements to be executed */
printf("Total purchase price and tendered amount");
scanf("%lf%lf", &price, &tendered);
printf("The sum of %lf and %lf is ", tendered,price);
changeDue=tendered-price;
while(changeDue!=0.00){
if(changeDue<=100.00){
changeDue=changeDue-100.00;
hundred=hundred+1;
}
if(changeDue<=20.00){
changeDue=changeDue-20.00;
twenty=twenty+1;
}
if(changeDue<=10){
changeDue=changeDue-10.00;
ten=ten+1;
}
if(changeDue<=5){
changeDue=changeDue-5.00;
five=five+1;
}
if(changeDue<=2){
changeDue=changeDue-2.00;
toonoe=toonoe+1;
}
if(changeDue<=1){
changeDue=changeDue-1.00;
loonie=loonie+1;
}
if(changeDue>1){
for(int i=0;i<changeDue;i++){
if(i==0.25&&changeDue>=0.25){
changeDue=changeDue-0.25;
quarter=quarter+1;
}
if(i==0.10&&changeDue>=0.10){
changeDue=changeDue-0.10;
dime=dime+1;
}
if(i==0.05&&changeDue>=0.05){
changeDue=changeDue-0.05;
nickle=nickle+1;
}
if(i==0.01&&changeDue<0.05){
changeDue=changeDue-0.01;
penny=penny+1;
}
}
}
}
if(hundred!=0){
printf("%d hundred$ bills given as change",hundred);
}
if(twenty!=0){
printf("%d twenty$ bills given as change",twenty);
}
if(ten!=0){
printf("%d ten$ bills given as change",ten);
}
if(five!=0){
printf("%d five$ bills given as change",five);
}
if(toonoe!=0){
printf("%d toonie coins given as change",toonoe);
}
if(loonie!=0){
printf("%d loonie coins given as change",loonie);
}
if(quarter!=0){
printf("%d quarter coins given as change",quarter);
}
if(dime!=0){
printf("%d dime coins given as change",dime);
}
if(nickle!=0){
printf("%d nicke coins given as change",nickle);
}
if(penny!=0){
printf("%d penny coins given as change",penny);
}
return 0;
}
I have an alternative version of that code, which changes the first part of scanning and printing to
/* identical to start of first version ... */
/* Statements to be executed */
printf("Total purchase price");
scanf("%d", &price);
printf("Enter amount recieved by customer ");
scanf("%d", &tendered);
printf("%d", &tendered);
printf("%d",&tendered);
changeDue=tendered-price;
/* identical to end of first version ... */
And I have a third version, where first scanning and printing is like this.
/* identical to start of first version ... */
float tendered;
float changeDue;
float price;
int hundred=0;
int twenty=0;
int ten=0;
int five=0;
float toonoe=0;
float loonie=0;
float quarter=0;
float dime=0;
float nickle=0;
float penny=0;
/* Statements to be executed */
printf("Total purchase price");
scanf("%f", &price);
printf("Enter amount recieved by customer ");
scanf("%f", &tendered);
printf("%f tendered", tendered);
changeDue=tendered-price;
/* identical to end of first version ... */
You have the problem of comparing a floating point value for identity
(or for not being identical, same problem) here:
while(changeDue!=0.00){
See here for some background:
Is floating point math broken?
It creates an endless loop (at least if you are not "lucky"), which prevents all further printing. (Actually "lucky" is not a good description for hiding a bug...)
In order to verify this diagnose, insert a printf at the start of the loop.
while(changeDue!=0.00){
printf("Making change...\n");
You will see many more of that debug output line than you expect.
In order to solve that endless-loop problem, change to
while(changeDue>=0.01)
and the endless loop is solved, which currently prevents anything visible happen after printing the due amount.
This does not necessarily fix all the problems in your code, but the most prominent one described in your question is solved.
Note that one of the comments recommends to use int for currency.
I normally agree, but I have accepted your statement that you have to use float/double.
By the way, use the first version of the code.
In the second version you are printing the address of something instead of the value. I.e. the & is wrong here:
printf("%d", &tendered);
In the third version your types and the format string in printf do not match.
I'm trying to prevent the user from entering a wrong value in this simple C program by using an if statement within while loop. But the problem is that whenever the user enters a wrong value, it gets stored in the variable and the same value is then use for further calculations.
Here's the actual program:
#include <stdio.h>
#include <stdlib.h>
/*Program to calculate the marks obtained scored by the class in a quiz*/
int main()
{
float marks, average, total = 0.0;
int noStudents;
printf("Enter the total number of students: ");
scanf("%d", &noStudents);
int a=1;
while(a<=noStudents)
{
printf("Enter marks obtained out of 20: ");
scanf("%f", &marks);
if(marks<0 || marks >20)
{
printf("You have entered wrong marks\nEnter again: ");
scanf("%d", &marks);
}
total = total+marks;
a++;
}
average = total/(float)noStudents;
printf("Average marks obtained by the class are: %f", average);
return 0;
}
The first problem is the inconsistency in your code. Inside the condition statement body, you wrote
scanf("%d", &marks);
which uses mismatched argument type for %d. This invokes undefined behavior. You should be using %f, as before.
That said,
you're relying on user to correct themselves in the second attempt, don't do that. Use a loop and only after you get a valid value, break out of that.
In the statement average = total/(float)noStudents;, you don't need the cast. One of the operand, total is already of float type, so the other operand will be automatically promoted and floating point division will take place, even in absence of the explicit cast.
Have slightly tweaked your code. Hope it helps. As already mentioned in one of the comment, don't expect user to give the correct value in out of range scenario. You should keep on asking the user to enter within the range unless he feeds in the correct value.
#include<stdio.h>
#include<stdlib.h>
int main()
{
float marks, average, total = 0.0;
int noStudents;
printf("Enter the total number of students: ");
scanf("%d", &noStudents);
int a=1;
while(a<=noStudents)
{
printf("Enter marks obtained out of 20: ");
scanf("%f", &marks);
if(marks<0 || marks >20)
{
printf("You have entered wrong marks.Enter again:\n ");
continue;
}
total = total+marks;
a++;
}
average = total/noStudents;
printf("Average marks obtained by the class are: %f", average);
return 0;
}
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 &.
I'm trying to practice making if-statements and am having very little luck with this. Right now I'm trying to make a trigonometric calculator, a very simple one, using if statements, but I can't get it working. The actual problem occurs after input the trig function (sine, cosine, tangent). This is what happens.
1. I compile it
2. It outputs the user prompt
3. I input the function and hit enter
4. The program jumps to a new blank line
5. Nothing happens and the program closes if I press enter
Here is the code itself. Please be kind if I've done something monumentally stupid, I'm pretty new to C.
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
float x;
float a, o, h;
float sine, cosine, tangent;
printf("Enter the trig function you wish to calculate: ");
scanf("%f", &x);
if (x == sine)
{ printf("Enter the value of the opposite leg: ");
scanf("%f", &o);
printf("Enter the value of the hypotenuse: ");
scanf("%f", &h);
sine = o / h;
printf("The sine is equal to %f", sine);
}
if (x == cosine)
{ printf("Enter the value of the adjacent leg: ");
scanf("%f", &a);
printf("Enter the value of the hypotenuse: ");
scanf("%f", &h);
cosine = a / h;
printf("The cosine is equal to %f", cosine);
}
if (x == tangent)
{ printf("Enter the value of the opposite leg: ");
scanf("%f", &o);
printf("Enter the value of the adjacent leg: ");
scanf("%f", &a);
tangent = o / a;
printf("The tangent is equal to %f", tangent);
}
getch();
}
Thank you to everyone who who was actually helpful and wasn't rude about my lack of understanding, I didn't realize I had to add a numerical character instead of just a character.
Simple (minimal) fixes
Yes, you're on the verge of doing various things that an experienced programmer would call silly, but they're the sorts of mistakes that novices make (you're neither the first nor the last to make them).
int main(void)
{
float x;
float a, o, h;
float sine, cosine, tangent;
printf("Enter the trig function you wish to calculate: ");
scanf("%f", &x);
if (x == sine)
The primary problem is that you've not given sine, cosine or tangent values, so you've no idea what to enter to make the equality work.
The secondary problem is that comparing floating point numbers for equality is not a good idea.
You'd probably do best with something like:
int main(void)
{
int x;
float a, o, h;
enum { sine, cosine, tangent };
printf("Enter the trig function (0 = sine, 1 = cosine, 2 = tangent): ");
scanf("%d", &x);
if (x == sine)
This is more or less orthodox, and reading and comparing integers for equality is reliable. You would have to change the actions since I've pre-empted the names sine, cosine, and tangent as enumeration (integer) constants. You could work around that by using upper-case names for the constants (that's pretty orthodox), or using a prefix for the names, or ...
int main(void)
{
int x;
float a, o, h;
float sine, cosine, tangent;
enum { SINE, COSINE, TANGENT };
printf("Enter the trig function (0 = sine, 1 = cosine, 2 = tangent): ");
scanf("%d", &x);
if (x == SINE)
Friendlier input
As you might gather from the comments below, it would be better to allow the user to enter the name of the function they'd like to enter instead of making them enter a coded number. That's a little trickier to code up reliably, which is the main reason why I left the answer above using numbers.
#include <stdio.h>
#include <string.h>
int main(void)
{
char line[4096];
printf("Enter trig function you wish to calculate: ");
if (fgets(line, sizeof(line), stdin) != 0)
{
char *nl = strchr(line, '\n');
if (nl != 0)
*nl = '\0';
if (strcmp(line, "sine") == 0)
{
/* Process sine */
}
else if (strcmp(line, "cosine") == 0)
{
/* Process cosine */
}
else if (strcmp(line, "tangent") == 0)
{
/* Process tangent */
}
else
{
fprintf(stderr, "Unrecognized trig function (%s)\n", line);
}
}
}
The 4096 is simply a big round number that's so long that it is very unlikely that anyone will ever enter a line that is longer than that. If they do enter such a line, then GIGO and they get what they deserve (which will be a polite error message that the name they entered was not recognized).
This is still not wonderful code. It might be reasonable to strip leading and trailing white space, and maybe case-convert the input to lower case, and one of the messages should probably identify the valid function names. It would be possible to have the code loop repeatedly, but then you'd need a function to prompt and read the response, etc. All of which adds usability at the expense of more code which complicates things unnecessarily for a beginning programmer.
Your if statements aren't working because you're comparing the input value, x, with a floating point value that hasn't been set. I think what you want to do is this:
int x;
printf("Enter the trig function you wish to calculate\n");
printf("1=sine, 2=cosine, 3=tangent: ");
scanf("%d", &x);
if (x == 1)
{
// do sine
}
else if (x == 2)
{
// do cosine
}
else if (x == 3)
{
// do tangent
}
else
{
printf("I don't know that function.\n");
}
Monumentally stupid? Naw. It's an easy kind of mistake to make when you first start programming. Stick with it. We've all been there.
I'm not sure what you are entering into the program to begin with, but this is where your error is. If you are entering a character array (a "string"), and that is being passed to x, you can't compare that with a floating point value. Also, your sine, cosine, and tangent variables have no value/have not been assigned anything. To solve your issue, assign your variables a number, such as float sine = 1; and make sure what you enter into the command line to pass to x is a number. If you want to enter "cosine", and pass that value to x, then you will have to change your x variable to a char array, such as char[] x = "", and then change your sine, cosine, and tangent variables to be character arrays as well. If you do change your variables to arrays, remember to remove the & from the scanf statement, like this -> scanf("%s", x);.
Right now, this code:
float x;
float a, o, h;
float sine, cosine, tangent;
printf("Enter the trig function you wish to calculate: ");
scanf("%f", &x);
if(x == sine)
...reads a value into x, but then compares it to the current value of sine. Unfortunately, you haven't initialized sine, so it's comparing to some unknown, semi-random value.
When you compare to cosine and tangent, you're doing more of the same.
None of these comparisons has a meaningful result (e.g., they might easily all be true).
At a guess, you probably want to have the user enter a string, and compare that to the values "sine", "cosine", and "tangent", using strcmp.