Why does this code round the final answer? - c

your program should ask the user to enter the price of one carton of juice as well as the number of cartons being purchased. Note that since juice is an ordinary grocery item, no sales tax is charged on it.
Then, determine the final cost of buying orange juice under the BOGO offer.
int main() {
//variables
int carton, total;
float cost;
printf("What is the cost of one container of OJ in dollars?\n");
scanf("%4f", &cost);
printf("How many containers are you buying?\n");
scanf("%d", &carton);
if (carton % 2 == 0) {
total = (carton / 2) * cost;
} else {
total = (carton % 2) * cost + (carton - 1 / 2) * cost;
}
//output
printf("The total cost is $%d", total);
return 0;
}

You just typecast the carton to float before dividing it. In this way you can also use modulus(%) operator with it as it is actually a integer and you also divide it by 2 by typecasting it to float

First, if you want your total to be a float number and not 'rounded' because you are casting it to an int, then you must declare it as a float.
Also you have some more calculations in the code that since you are using integers, you are getting answers that you are not expecting. (e.g.carton - 1/2). I would highly recommend you to change all 3 of you variables to floats.
Secondly, in your last line you wrote:
printf("The total cost is $%d", total);
%d is used for integers
%f is used for floats
When you do %d to floats you are casting it. Meaning that it's the same as doing (int)total and since integers are only whole numbers, your total will also be a whole number.
So long story short.. If you want total to not be 'rounded', use this:
int main() {
//variables
float carton, cost, total;
printf("What is the cost of one container of OJ in dollars?\n");
scanf("%4f", &cost);
printf("How many containers are you buying?\n");
scanf("%f", &carton);
if (carton % 2 == 0) {
total = (carton/ 2)*cost;
}
else {
total = (carton % 2)*cost + (carton - 1/ 2)*cost;
}
//output
printf("The total cost is $%f", total);
return 0;

Related

C: 2 User input fields when requesting 3

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;
}

Calculations are not coming in, what am I doing wrong

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);

show decimal using C

I'm trying to show the decimal points after the number
#include <stdio.h>
int main() {
int weight;
int miles;
int price;
printf("Enter the packages weight \n");
scanf("%d", &weight);
printf("Enter how many miles to ship the package \n");
scanf("%d", &miles);
if(weight <= 15) {
price = 15;
}
else {
price = (15 + ((weight - 15) * .5 ));
}
if(miles % 500 == 0) {
price += (miles / 500 * 10);
}
else {
price += ((miles / 500 )* 10) + 10;
}
printf("It will cost $%d to ship an item weighing %d pounds %d miles \n", price, weight, miles);
return 0;
}
for the price = (15+((weight-15)*.5)); When I plug in the numbers outside of the console it shows the decimal places. I'm probably missing the most simple thing...
You should change the data type of the variable price to float (or double) if you wish to store some fractional part in it.
Also, since miles / 500 may create some decimal part (and miles itself can be floating-point!), it should also be made float or double.
Finally, in the printf arguments, do not forget to change the format specifier %d.
Prefer to use a floating-point data type for all the variables involved in some computation that might yield fractional numbers as it will be more comprehensible and if you wish to not see the decimal part in the output, then set the precision to 0 (%.0f).

Trying to write a code for a bill changer/coin vending kiosk

I'm trying to write a code for a bill changer where the amount of money inserted are converted back into coins for the user. The problem is I keep having decimals in my amount of 50c like 222.222 when i input 111.111. My 20c and 10c is unused.. Please help
#include <stdio.h>
int main()
{
double sum50c=0, sum20c=0, sum10c=0, remainder, remainder2, remainder3, end=0;
double amount;
do
{
printf("Please enter an amount(dollars):");
scanf("%lf", &amount);
amount=amount*100;
if(amount<0){
printf("Invalid Input\n");
printf("Re-enter your amount:");
scanf("%lf", &amount);
}
if(amount>=50){
remainder=amount/50;
sum50c=remainder;
}else
if(remainder!=0){
remainder2=remainder/20;
sum20c=remainder2;
}else
if(remainder2!=0){
remainder3=remainder3/10;
sum10c=remainder3;
}
if(sum50c>200||sum20c>200||sum10c>200){
end++;
}else{
end=0;
}
}
while(end<=0);
printf("The amount of 50cents=%lf, 20cents=%lf, 10cents=%lf", sum50c, sum20c, sum10c);
}
There are basically two errors in your code:
Don't operate on floating-point numbers here. The number of coins will be a discrete number, which should be represented as int or maybe even unsigned int. The amount itself may be read in as floating-point number for simplicity, but it should also be converted to the number of cents as integerin order to avoid rounding errors.
You have to find combinations of coins: 30c is 1%times;20c + 1×10c. That means that you can't use else if chains, which will only consider one type of coin. Treat all types of coin, highes denomination first, and then reduce the amount still to handle. Note that with 10c as smallest coin, you might not be able to give full change for all amounts.
Here's you example without the outer loop and without the strange end business:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int num50c = 0,
num20c = 0,
num10c = 0;
int amount; // amount in cents
double iamount; // input amount in dollars
printf("Please enter an amount: ");
scanf("%lf", &iamount);
amount = iamount * 100 + 0.5;
if (amount < 0) {
printf("Invalid Input\n");
exit(1);
}
num50c = amount / 50;
amount %= 50;
num20c = amount / 20;
amount %= 20;
num10c = amount / 10;
amount %= 10;
printf("%d x 50c = %d\n", num50c, num50c * 50);
printf("%d x 20c = %d\n", num20c, num20c * 20);
printf("%d x 10c = %d\n", num10c, num10c * 10);
printf("Remainder: %dc\n", amount);
return 0;
}
To force amount to have integer values you should round the value after your division:
if(amount>=50)
{
remainder=round(amount/50);
sum50c=remainder;
}

How to add total of multiple repeats in C?

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

Resources