Calculation producing whole number instead of a decimal - c

I have some code:
#include <math.h>
#include <stdio.h>
int main(void) {
int amount;
// user input for annual income
printf("Enter your amount: ");
scanf("%d", &amount);
if(amount <= 34000)
amount = amount * .33;
double new_amount = (double) amount;
printf("your calculated amount: %.2f\n", new_amout);
return 0;
}
I am trying to take in an integer value and then convert it to a double after making my calculation. However, when i enter my int, it prints a decimal but with no non-integer part.
For example, if my amount is 19522, my code prints 6442.00 instead of 6442.26.

The easiest fix is to change the data type of amount to double and update the format strings, and eliminate the new_amount variable as it doesn't do anything for you. Also, check that scanf() was successful otherwise you may be operating on uninitialized data:
#include <math.h>
#include <stdio.h>
int main(void) {
double amount;
printf("Enter your amount: ");
if(scanf("%lf", &amount) != 1) {
printf("scanf failed\n");
return 1;
}
if(amount <= 34000)
amount *= .33;
printf("your calculated amount: %.2lf\n", amount);
}

Related

Need help solving a issue involving 'function definition is not allowed here' in c language

Tried running this in C but it keeps saying "function definition is not allowed here" when referring to '{'. This is the full code that im trying to run, its called a "greedy algorithm" so im still learning how to make it. The program is supposed to give you your exact change back then let you know how many coins of which type will be needed.
#include <cs50.h>
#include <math.h>
int main()
{
int len = 4;
double cost;
double pay;
{
//promt user for cost
printf("Enter cost: ");
scanf("%lf", &cost);
//prompt user for pay amount
printf("Enter pay: ");
scanf("%lf", &pay);
double change = pay - cost;
if(pay > cost)
printf("Trasncation complete\nHeres your change: %f\n", change);
else if(pay == cost)
printf("Transaction complete.\n");
else if(pay < cost)
printf("insufficient funds\nStill need: %f", cost - pay);
//greddy algorithm
}
void greedy(double change)
{
int i=o;
double number;
double coin[len] = [0.01, 0.05, 0.10, 0.25];
while(i>len)
{
if(coin[i] <= change)
{
number = change / coin[i];
printf("%f of %f is needed", number, change);
change = change * coin[i];
}
i++
}
}
}
You have to define your greedy() function outside of the main function like so:
#include <cs50.h>
#include <math.h>
int main()
{
int len = 4;
double cost;
double pay;
{
//promt user for cost
printf("Enter cost: ");
scanf("%lf", &cost);
//prompt user for pay amount
printf("Enter pay: ");
scanf("%lf", &pay);
double change = pay - cost;
if(pay > cost)
printf("Trasncation complete\nHeres your change: %f\n", change);
else if(pay == cost)
printf("Transaction complete.\n");
else if(pay < cost)
printf("insufficient funds\nStill need: %f", cost - pay);
}
}
// greddy algorithm
void greedy(double change)
{
int i=o;
double number;
double coin[len] = [0.01, 0.05, 0.10, 0.25];
while(i>len)
{
if(coin[i] <= change)
{
number = change / coin[i];
printf("%f of %f is needed", number, change);
change = change * coin[i];
}
i++
}
}

Calculate the discount in a program in C language

I have a plan that gives the total price of the products and if the purchase is more than 200, it should give a 15% discount. But when displaying the final amount, it displays the zero:
#include <stdio.h>
#include <conio.h>
int main()
{
int count;
printf("plz enter number of product :");
scanf("%d", &count);
int price;
int allprice;
float discounted_price ;
int i = 0;
while(i<count)
{
printf("plz enter price %d : ",i+1);
scanf("%d", &price);
allprice +=price;
i++;
}
if(allprice>200)
{
float discount_amount = (15*allprice)/100;
float discounted_price = (allprice-discount_amount);
}
printf("price before discount : %d ",allprice);
printf("\n");
printf("price after discount : %d ",discounted_price);
return 0;
}
You have discounted_price twice.
Once where you calculate it inside the if.
Once outside, which you output.
Outputting hence ignores the calculated value.
Change
float discounted_price = (allprice-discount_amount);
to
discounted_price = (allprice-discount_amount);
And you also need to change the way of printing it, to match the float type
(and thereby avoid undefined behaviour).
printf("price after discount : %f ",discounted_price);
Finally, the amounts will be more precise if you avoid the integer division:
float discount_amount = (15*allprice)/100.0;
And for good measure, init the summation variable (though the effect of that is not always seen) :
int allprice =0;
For readining input by a human (i.e. prone to format errors) it would be wise to check the return value of scanf() and use other verification techniques. But that is beyond the scope of an answer to your question.
First, you should initialize allprice to zero in order to calculate the total.
The inital value of the variable, if not initialized is undefined.
The expression
(15*allprice)/100;
may result in zero because it's doing integer divion since all of the operands (15, allprice, 100) are integers. To avoid this, you can just convert one of the operands to a float, or just add a .0 after 100.
(15*allprice)/100.0f;
This should fix your problem. Let me know if it helps.
The resulting code should look like this:
#include <stdio.h>
#include<conio.h>
int main(){
int count;
printf("plz enter number of product :");
scanf("%d", &count);
int price;
int allprice = 0;
float discounted_price ;
int i = 0;
while(i<count)
{
printf("plz enter price %d : ",i+1);
scanf("%d", &price);
allprice +=price;
i++;
}
if(allprice>200)
{
float discount_amount = (15*allprice)/100.0f;
discounted_price = (allprice-discount_amount);
}
printf("price before discount : %d ",allprice);
printf("\n");
printf("price after discount : %f ",discounted_price);
return 0;
}

Error using scanf: return value ignored with floating point

this is my code and I'm not sure why I'm getting an error whenever I try to test it. It keeps saying return value ignored with scanf
#include <stdio.h>
#include <math.h>
int main(void) {
float money, tax, result;
printf("Enter the amount of money.");
scanf("%f", &money);
tax = 0.05 * money;
result = tax + money;
printf("With tax added: $%f", result);
return 0;
}
It is because return value is ignored.
You should check return values of scanf() to check if readings are successful.
#include <stdio.h>
#include <math.h>
int main(void) {
float money, tax, result;
printf("Enter the amount of money.");
if (scanf("%f", &money) != 1) {
fputs("read error!\n", stderr);
return 1;
}
tax = 0.05 * money;
result = tax + money;
printf("With tax added: $%f", result);
return 0;
}

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

Working with scanf and loops in functions

I want to use a function to ask the user for a balance. If the balance is below 0 the user is prompted to enter a value above 0. Here is the code I have done so far:
#include <stdio.h>
#include <string.h>
float getPositiveValue();
int main()
{
float begbal;
begbal = getPositiveValue();
getPositiveValue();
printf("balance: %f\n", begbal);
return 0;
}
float getPositiveValue()
{
float money;
printf("Please enter the beginning balance: \n");
scanf("%f", &money);
if(money < 0)
{
printf("Enter a balance amount above 0:");
scanf("%f", &money);
}else{
}
}
I get the error "warning: control reaches end of non-void function". I know I need to end the else statement, but not sure what to put in there if they did enter a value above 0. Also, when the program is run it asks the user twice to enter the beginning balance for some reason. Seems like this should be a simple fix, for some reason I have trouble getting my head around functions heh.
Any help much appreciated.
revised working code(thanks):
#include <stdio.h>
#include <string.h>
float getPositiveValue();
int main()
{
float begbal;
begbal = getPositiveValue();
printf("balance: %f\n", begbal);
return 0;
}
float getPositiveValue()
{
float money;
printf("Please enter the beginning balance: \n");
scanf("%f", &money);
while(money < 0)
{
printf("Enter a balance amount above 0:");
scanf("%f", &money);
}
return money;
}
getPositiveValue() is supposed to return a value (float). You could add return money; before its closing }.
What if the user is particularly dense and doesn't enter a positive amount? Do you want to give them only one chance? If not, you probably want to use a while (money < 0.0) loop.
You need to return a float value, so in this case you can return money.
You are calling your function twice in the main function.
begbal = getPositiveValue();
getPositiveValue();
Just remove the last statement
"Also, when the program is run it asks the user twice to enter the
beginning balance for some reason."
because you have called function getPositiveValue() TWICE IN YOUR CODE
and your function needs to return the float value which is "money" in this case.
The user could persist in entering the wrong thing, so you need a loop to iterate till they get it right. Also, you need to return a value from this function.
float getPositiveValue()
{
float money;
fputs("Please enter the beginning balance: ", stdout);
for (;;) {
scanf("%f\n", &money);
if (money >= 0)
break;
fputs("Balance must be nonnegative.\n"
"Please enter the beginning balance: ", stdout);
}
return money;
}
But that's only the tip of the iceberg here. scanf should never be used, and floating-point numbers should not be used to keep track of money. What you should really be doing here is reading a line of text with getline (or fgets, if getline is unavailable), and parsing it with strtoul and custom logic, presumably as [$]dddd[.cc] (where square brackets indicate optional text), into a uint64_t value scaled to cents.
As the user may enter an invalid range (a negative number) or non-numeric text, need to consume offending input before next prompt.
float getPositiveValue() {
float money = 0.0;
printf("Enter a balance amount above 0:");
while ((scanf("%f", &money) != 1) || (money < 0)) {
int ch;
while (((ch = fgetc(stdin)) != '\n') && (c != EOF));
if (c == EOF) break;
printf("Enter a balance amount above 0:");
}
return money;
}

Resources