Should I change something in written code? Compiler says that everything is right — no errors or warnings.
Please write a C program that calculates the cost of the cement you will have to purchase to build your foundation.
My code so far:
#include <stdio.h>
#include <math.h>
int main(void) {
int price=45, totalPrice, OneBag=120;
float needed;
do
{
printf("Enter the amount of cement you need for your foundation that is not dividable by 120: ");
scanf("%f", &needed);
} while (fmodf(needed, OneBag)==0);
totalPrice = ((int)needed/OneBag+1)*(price);
printf("Total cost of cement you will need for your foundation is %d", totalPrice);
return 0;
}
To be honest, I don't see any real mistakes in your code, but in my opinion, there is room for improvement:
Price per bag and size of a bag, are both constants, which you can actually make clear in your code, this is more readable and it allows the compiler to optimize your code better.
You also don't actually have to check if the input is a multiple of 120, because it is a given that it is not.
There is also something called the ceil
function (or ceilf
if working with floats), which actually takes any number and increases upward to the nearest integer. Which is pretty useful for this assignment.
One last thing just because the compiler says it's all right, doesn't mean it actually is.
code:
#include <stdio.h>
#include <math.h>
const float price_per_bag = 45;
const float bag_size = 120;
int main(void) {
float needed;
printf("Enter the amount of cement needed:\n");
scanf("%f", &needed);
float price = ceilf(needed / bag_size) * price_per_bag;
printf("total price: %i\n", (int)price);
}