From what I understand I should be getting 3 user input prompts, Trip Distance, Car MPG, and Gas Dollars Per Gallon to calculate total trip cost. Whenever I run the code, I only get prompted to input trip distance and car mpg, it skips gas dpg. How do I get it to recognize 3 user inputs?
int main() {
int miles;
double milesPG;
double dollarsPG;
double gasCost = (miles * (1.0 / milesPG) * dollarsPG);
printf("Input trip distance: ", miles);
scanf("%d", &miles);
printf("\nInput car miles per gallon: ", milesPG);
scanf("%0.2lf", &milesPG);
printf("\nInput gas dollars per gallon: ", dollarsPG);
scanf("%0.2lf", &dollarsPG);
printf("\nTotal trip cost is %0.2lf \n", gasCost);
return 0;
}
There are multiple problems in your code:
you do not include <stdio.h>
you compute gasCost before the values of miles, milesPG and dollarsPG are input. Since these variables are uninitialized, this has undefined behavior.
passing the uninitialized values to the printf() statements for prompting is useless and actually has undefined behavior as these variables are uninitialized.
the conversion format "%0.2lf" is invalid for scanf(). You cannot specify how many places to input, just the maximum number of bytes to read, which is not useful in your case.
Here is a modified version:
#include <stdio.h>
int main() {
int miles;
double milesPG;
double dollarsPG;
printf("Input trip distance: ");
if (scanf("%d", &miles) != 1)
return 1;
printf("\nInput car miles per gallon: ");
if (scanf("%lf", &milesPG) != 1)
return 1;
printf("\nInput gas dollars per gallon: ");
if (scanf("%lf", &dollarsPG) != 1)
return 1;
double gasCost = (miles * (1.0 / milesPG) * dollarsPG);
printf("\nTotal trip cost is %.2f\n", gasCost);
return 0;
}
Related
I am new to C programming and cannot seem to get the calculations for the code below to come in outside of the one calculation when I input 1 for distance which then calculates to $1.80. I have an if else that should recognize that as not meeting the minimum and therefore calculate it as $5.00, but it just calculates $1.80. Can you please point me in the right direction as to what I am missing for the needed calculations?
#include <stdio.h>
#include <stdlib.h>
#define MINFARE '$5.00'
int main() {
//Declare all of the variables types and their data types and values as applicable.
float distance, totalFare;
int numberOfPassengers, airport;
//Prompt passenger to enter the total distance (measured to 1/10 of a mile) with a keyboard
printf("Please enter the total distance, ");
printf("enter it measured to 1/10 mile, e.g. 25.5: ");
scanf("%f", &distance);
//Prompt the user to enter the number of passengers
printf("\nPlease enter the number of passengers: ");
scanf("%d", &numberOfPassengers);
printf("\nAre you going or coming from the Airport? ");
printf("Enter (1) for <yes> and (2) for <no>: ");
scanf("%d", &airport);
if(airport == 1) {
totalFare = (1.80 * distance) + 2.00;
}
else {
totalFare = 1.80 * distance;
}
/*Calculate the fare amount with the number of passengers, such that, the initial rider is charge the fare only,
the first additional passenger charge is the fare plus $1.00 and additional passengers are charge an additional
$0.50 per passenger*/
if (numberOfPassengers <= 1) {
totalFare = 1.80 * distance;
}
else {
totalFare = (1.80 * distance) + 1.00 + (0.50 * (numberOfPassengers - 1));
}
printf("\nYou entered %g as the total miles, %d passengers, and %d for Airport cab ride.", distance, numberOfPassengers, airport);
if (totalFare>5.00) {
printf("\nThe total fare owed is:\t MINFARE.");
}
else {
//Print the statements below based on the user input and the calculations total Fare for cab ride
printf("\nThe total fare owed is:\t $%.2f",totalFare);
}
return 0;
}
I agree with #MikeCAT, but just want to clarify this part about symbolic constant (#define MINFARE '$5.00'). In C single quotes (' ') represents a single character, not a string (You are probably confusing it with some other languages like python that works diferently). As already pointed what you write is a multi-character character literal and not string what you actually wanted. If you want to define a string in C you must use double quotes (" ") (Because even a single character string actually have two characters, that one and '\0' which is an indicator that marks the end of a string).
You are limitting the maximum instead of minimum and goint to print a string "MINFARE" when the maximum is hit.
One fix is:
totalFare>5.00 should be totalFare<5.00 to have the value work as minimum, not maximum.
#define MINFARE '$5.00' should be #define MINFARE "$5.00".
printf("\nThe total fare owed is:\t MINFARE."); should be printf("\nThe total fare owed is:\t " MINFARE ".");
Better fix avoiding using magic number is:
#define MINFARE '$5.00' should be #define MINFARE 5.00
totalFare>5.00 should be totalFare<MINFARE
printf("\nThe total fare owed is:\t MINFARE."); should be printf("\nThe total fare owed is:\t $%.2f.", MINFARE);
Working with Repl.it and trying to use a function in C to average the elements in a variable length array. My program works fine in every other i/o area other than the average which returns:
The average for that day is: -nan. Any insight on what the issue may be?
The goal is to receive user input as a double(for example, how many pints of blood were taken per hour over a 7 hr period and then use a function call to calculate the average amount for that seven hour period.
New code is as follows:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double average(int size, float ary[*]);
int main(void)
{
char dayOne[8], dayTwo[8];
int size;
float ave;
printf("Over how many hours do you want to view donation amounts?: ");
scanf("%d", &size);
if (size < 7 || size > 7)
size = 7;
printf("Enter day that you want to see average donation amount for: ");
scanf("%s", dayOne);
{
float ary[size];
for (int i = 0; i < size; i++)
{
printf("\nEnter amount taken in hour %d:", i + 1);
scanf("%f", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average donated for %s is: %2.1f", dayOne, ave);
}
printf("\n\nEnter day that you want to see average donation amount for: ");
scanf("%s", dayTwo);
if(strcmp(dayOne, dayTwo)== 0)
printf("\nEnter a different day please: ");
scanf("%s", dayTwo);
{
float ary[size];
for (int i = 0; i < size; i++)
{
printf("\nEnter amount taken in hour %d:", i + 1);
scanf("%f", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average donated for %s is: %2.1f", dayTwo, ave);
}
return 0;
}
double average(int size, float ary[])
{
double sum = 0;
double ave;
for (int i = 0; i < size; i++)
sum += ary[i];
ave = (double)sum / size;
return ave;
}
This is wrong:
int ary[7];
…
scanf("%f", &ary[i]);
%f is for scanning a float, but ary[i] is an int. The resulting behavior is not defined.
This is wrong:
double size;
…
ave = average(size, ary);
Nothing in the “…” assigns a value to size, so it has no defined value when average is called.
Quite a few syntactical and logical changes to be made buddy. As Eric Postpischil has mentioned in his answer, your size variable isn't initialized to anything before use. And using %f for accepting integers is incorrect too. Along with these, there are a few other glitches which I will list below, with the corresponding fixes. I have also attached the full working code along with the output.
Error: size variable not initialized.
Fix:: Since you have a fixed number of hours, you can either use the 7 directly or through size. Hence initialize the variable while declaring it. And just a suggestion buddy, use int for size. ==> int size = 7;
Error: Accepting input for array values. The array ary is of type int, but you have used %f which is a format specifier for float.
Fix: Use %d which is the format specifier for int data type. ==> scanf("%d", &ary[i]);
Error: Format specifier used for printing the average value. You have used %f again which is for float while the variable ave for average if of type double.
Fix: Use %lf which is the format specifier for double. ==> printf("\nThe average for the 2nd day is: %.3lf", ave); The .3 before lf is just to limit the number of decimal points to 3. It is optional.
Error: You accept the second day and display a message if it is the same as the first day, but the scanf for this is out of the if loop. hence it prompts the user to input another name of the day regardless of whether the second input day is same as the first or not.
Fix: just move that scanf into the if loop where you check if that day is same as the previous one.
I wouldn't really call this one an error, because it's just an improvement which I find that needs to be done. You accept the second day which should be different from the first with the message that average would be found. But you are not calculating the average for this day. Hence I have included that part in the code.
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double average(int, int [7]);
int main(void)
{
char dayOne[8], dayTwo[8];
int size = 7;
double ave;
printf("Enter day that you want to see average donation amount for: ");
scanf("%s", dayOne);
int ary[7];
for (int i = 0; i < 7; i++)
{
printf("Enter amount taken in hour %d:", i + 1);
scanf("%d", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average for the 1st day is: %.3lf", ave);
printf("\n\nEnter day that you want to see average donation amount for:");
scanf("%s", dayTwo);
if(strcmp(dayOne, dayTwo)== 0) {
printf("\nEnter a different day please: ");
scanf("%s", dayTwo);
}
for (int i = 0; i < 7; i++)
{
printf("Enter amount taken in hour %d:", i + 1);
scanf("%d", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average for the 2nd day is: %.3lf", ave);
return 0;
}
double average(int size, int ary[7])
{
int sum = 0;
double ave;
for (int i = 0; i < size; i++) {
sum = sum + ary[i];
}
ave = sum / size;
return ave;
}
OUTPUT:
Enter day that you want to see average donation amount for: Day1
Enter amount taken in hour 1: 1
Enter amount taken in hour 2: 2
Enter amount taken in hour 3: 3
Enter amount taken in hour 4: 4
Enter amount taken in hour 5: 5
Enter amount taken in hour 6: 6
Enter amount taken in hour 7: 7
The average for the 1st day is: 4.000
Enter day that you want to see average donation amount for: Day2
Enter amount taken in hour 1: 8
Enter amount taken in hour 2: 8
Enter amount taken in hour 3: 8
Enter amount taken in hour 4: 8
Enter amount taken in hour 5: 8
Enter amount taken in hour 6: 8
Enter amount taken in hour 7: 8
The average for the 2nd day is: 8.000
Hope this helps.
double size;
The size variable has not been set before calling the average function.
ave = average(size, ary);
May be size can be initialized to 0 and incremented in the for loop as given below
double size = 0;
double ave;
printf("Enter day that you want to see average donation amount for: ");
scanf("%s", dayOne);
{
int ary[7];
for (int i = 0; i < 7; i++)
{
printf("Enter amount taken in hour %d:", i + 1);
scanf("%f", &ary[i]);
size++;
}
ave = average(size, ary);
printf("\nThe average for the day is: %f", ave);
}
If the goal is to receive user input as a double, the array used to hold those values should be double.
double ary[7];
instead of
int ary[7];
I'm in school learning C. (I am not asking for anyone to write this for me).
Assignment
This program will calculate the miles per gallon MPG for you for three tanks of gas after you have entered the gallons used and miles driven.
I can get my program to start a loop, but I can't figure out how to make it end the loop after 3 runs and give me the Average MPG in 3 tanks. Running the program give me the average, but will keep asking forever.
#include <stdio.h>
int main(void) {
int miles;
float gallons = -1, mg, overall = 0, avg = 0;
while(gallons != 0) {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;
}
return 0;
}
Try this small changes. Use an iterator to get average of 3 tanks.
Modify like
i=0;
while(i < 3) {
i++;
#include <stdio.h>
int main(void) {
int miles, **i=0;**
float gallons = -1, mg, overall = 0, avg = 0;
**while(i < 3)** {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;
**i++;**
}
return 0;
}
Sorry: I did not see how is gallons being assigned/initialized in your code, I saw float galons and while (gallons != 0) and then thought that gallons was at some point the result of a computation.
This answer is still useful in my opinion.
Don't use float values to check conditions, floats are not accurate because their machine representation cannot be, so gallons != 0 will probably hardly ever be true, use int instead and your loop control will work correctly. Only use float for the average value.
But in fact, because your specific problem can be solved with a for loop, you should use
for (int i = 0 ; i < 3 ; ++i)
instead, that way you know that it will only loop 3 times.
SIDE NOTE: learn more about scanf() and why you MUST check the value that it retuns in programs like yours.
Your program, as written, does not stop at 3 tanks. It will continuously ask for tanks until you answer 0 to the number of gallons used.
To make it read at most three tanks, replace while (gallons != 0) with for (int i = 0; i < 3; i++). That will make the main loop run three times only.
But then it won't print the overall average. It will simply quit after running three times. The code that shows the overall average is inside that if test that checks if you typed 0 gallons. Remove that if test and move the printf statement which shows the overall average near the end of the program, right before the return statement. This way it will run after the for loop runs 3 times.
float gallons = -1;
It doesn't make any sense;
And you need to notice one thing that is
while(gallons!=0){
//code
}
You are asking the user to enter the value if gallons to input and your not changing it's value so this value will always be true in while and loop will go infinite.
If you need to run the loop three times then you can do it by using variable.
`
int i=3;
while(i>0){//code
i--;
}
Here I have edited your program ;
#include <stdio.h>
int main(void) {
int miles,i=3;
float gallons, mg, overall = 0, avg = 0;
while(i>0) {
printf("Enter the gallons used: ");
scanf("%f", &gallons);
if (gallons == 0) {
printf("\n\n The overall miles/gallon was: %f\n", overall/avg);
exit(0);
}
printf("Enter miles driven: ");
scanf("%d", &miles);
mg = miles/gallons;
printf("The miles/gallon for this tank was : %f\n", mg);
overall += miles;
avg += gallons;i--;
}
return 0;
}
`
I am writing a simple C program which takes data from user and does some maths. Here is my code:
#include <stdio.h>
int main(void) {
int semester_1,grade_1,grade_2,grade_3,subtotal,total_marks,average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = subtotal / 300 * 100;
printf("Your average this semester is %d", total_marks);
semester_1--;
}
average = semester_1 / 100 * total_marks;
printf("Your final average for all semesters is %d", average);
}
The problem with this code is that when I run the program returns 0 for final average for all semesters.
I wanted to get the final average for all semesters. Lets say if user enters 3 for numbers of semester they want to check and then they will be enter marks 3 times and then final average will be displayed, but it only gives 0.
#include <stdio.h>
int main(void) {
int semester_1,grade_1,grade_2,grade_3,subtotal,total_marks,average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = subtotal / 300.0 * 100.0;
printf("Your average this semester is %d", total_marks);
semester_1--;
}
average = semester_1 / 100.0 * total_marks;
printf("Your final average for all semesters is %d", average);
}
Rounding errors
It is probably because here:
total_marks = subtotal / 300 * 100;
subtotal is less than 300 * 100. And since both the operands of / are of type int, integer division is performed resulting in total_marks becoming 0.
Fix it by changing the type of total_marks to float, or more preferably, double. Then, cast one of the operands of / to float if you changed total_marks's type to float or double if you changed total_marks's type to double. The cast makes sure that integer division is not performed and floating-point division is performed.
You might need to do the same with average.
Fixed Code:
#include <stdio.h>
int main(void) {
int semester_1, grade_1, grade_2, grade_3, subtotal; /* Better to use an array */
double total_marks, average;
printf("Enter number of semester you to check");
scanf("%d", &semester_1);
while (semester_1 > 0) {
printf("Enter marks for first subject");
scanf("%d", &grade_1);
printf("Enter marks for second subject");
scanf("%d", &grade_2);
printf("Enter marks for third subject");
scanf("%d", &grade_3);
subtotal = grade_1 + grade_2 + grade_3;
total_marks = (double)subtotal / 300 * 100; /* Note the cast */
printf("Your average this semester is %f", total_marks); /* Note the change in the format specifier */
semester_1--;
}
average = (double)semester_1 / 100 * total_marks; /* Note the cast */
printf("Your final average for all semesters is %f", average); /* Note the change in the format specifier */
}
Your code has several issues. The first is the one pointed out by Cool Guy: dividing small integer by bigger integer will lead to the result being zero due to integer truncation.
The second is that you aren't keeping a running total, and you're decrementing the number of semesters for your loop counter.
You should add a new variable that stores the cumulative sum of each semester, and you should save the initial value of semester_1
(Also, style-wise,
for (int i = 0; i < num_semesters; i++)
is much more readable than (and preserves the value of num_semesters)
while(semester_1 > 0)
)
Im trying to write this code for school, and im absoultly stuck on what im doing wrong, if anyone could just point me in the right direction, that would be helpful. Trying to learn as much as i can.
My program doesnt calculate out, how much is owed at the end of each month, after subtrackting the payment, and then adding the interest.
IT just displays the same value.
#include<stdio.h>
int main()
{
float loan;
float interest;
int n;
float outstanding;
float outstanding2;
float princeable;
float payment;
printf("\nEnter the amount of the loan: \n ");
scanf("%f" , &loan);
printf("\nEnter monthly interest percentage\n ");
scanf("%f" , &interest);
printf("\nEnter monthly payments: \n ");
scanf("%f" , &payment);
printf("\nEnter number of monthly Payments: \n ");
scanf("%i" , &n);
while (n >= 0) {
outstanding = (loan - payment);
outstanding = (outstanding * (1 + (interest/100)));
printf("\Outstanding Balance after %i =%.2f\n\n", n, outstanding);
n--;
}
return 0;
}
In each iteration, you should calculate outstanding based on its previous value, and not on the initial loan's value, because you also pay interest for interest.
outstanding = loan;
while (n > 0) {
outstanding = (outstanding - payment);
outstanding = (outstanding * (1 + (interest/100)));
printf("\Outstanding Balance after %i =%.2f\n\n", n, outstanding);
n--;
}
This line:
outstanding = (loan - payment);
within the loop is incorrect since it starts with the initial loan value each time. It should be:
outstanding = (outstanding - payment);
You'll also have to set outstanding to loan before entering the loop.
On top of that, you have one too many loop iterations, and an illegal escape sequence \O in your printf string.