Can anyone point out what mistake I made in my code? - c

Pooja would like to withdraw X $US from an ATM. The cash machine will
only accept the transaction if X is a multiple of 5, and Pooja's
account balance has enough cash to perform the withdrawal transaction
(including bank charges). For each successful withdrawal the bank
charges 0.50 $US. Calculate Pooja's account balance after an attempted
transaction.
#include <stdio.h>
int main(void)
{
float initialamt;
int deductamt =0;
// taking input of the account balance and money to be withdrawn
scanf("%f", &initialamt);
scanf("%d", &deductamt);
// Checking if the mat is a multiple of 5 and less than act balance
if(deductamt%5 ==0 && deductamt<= initialamt-0.50)
{
initialamt = initialamt - deductamt -0.50;
printf("%2f", initialamt);
}
else
{
printf("%2f", initialamt);
}
return 0;
}

I found the question on CodeChef, is your question https://www.codechef.com/problems/HS08TEST?
Then what the question input is deduct - init balance in order, but not init balance - deduct in order, so just switch the scanf.
scanf("%d", &deductamt);
scanf("%f", &initialamt);

Related

Correct outputs but codechef says wrong while submitting the code

Link to the problem : https://www.codechef.com/problems/HS08TEST
Description
Pooja would like to withdraw X $US from an ATM. The cash machine will only accept the transaction if X is a multiple of 5, and Pooja's account balance has enough cash to perform the withdrawal transaction (including bank charges). For each successful withdrawal the bank charges 0.50 $US. Calculate Pooja's account balance after an attempted transaction.
Input
Positive integer 0 < X <= 2000 - the amount of cash which Pooja wishes to withdraw.
Nonnegative number 0<= Y <= 2000 with two digits of precision - Pooja's initial account balance.
Output
Output the account balance after the attempted transaction, given as a number with two digits of precision. If there is not enough money in the account to complete the transaction, output the current bank balance.
Example - Successful Transaction
Input:
30 120.00
Output:
89.50
Example - Incorrect Withdrawal Amount (not multiple of 5)
Input:
42 120.00
Output:
120.00
Example - Insufficient Funds
Input:
300 120.00
Output:
120.00
I unable to find any incorrect output when I change the parameters in transaction function but still I am unable to submit it successfully due to some error which I am not able to find. This is my first try with codechef or in fact with any competitive programming so any help will be appreciated.Here's my code:
#define count 0.5
float transaction(int , float);
int main(void)
{
float transaction(int x, float acc_bal)
{
float z=acc_bal-(x+count);
if(x<acc_bal)
{
if(x%5==0)
{
printf("%.2f",z);
}
}
if(x%5!=0)
{
printf("%0.2f",acc_bal);
}
}
transaction(42,120.00);
}
Functions inside functions is not standard C. Some compilers supports it, but then you rely on compiler extensions. Do like this:
#include <stdio.h>
#define count 0.5
float transaction(int x, float acc_bal)
{
float z=acc_bal-(x+count);
if(x<acc_bal)
{
if(x%5==0)
{
printf("%.2f",z);
}
}
if(x%5!=0)
{
printf("%0.2f",acc_bal);
}
}
int main(void)
{
transaction(42,120.00);
}
But your code is unnecessarily messy and is missing the case where x is greater than the balance. Also, it does not need to be declared as a float. I would write like this instead:
void transaction(int x, float acc_bal)
{
const float count = 0.5;
float after=acc_bal-(x+count);
if(x%5 == 0 && after>=0.0) {
printf("%.2f\n",after);
} else {
printf("%0.2f\n",acc_bal);
}
}
Besides the function-in-function stuff and a missing return value (which isn't used btw), the problem is that you never check if the account goes negative.
Check what happens if you call your code with transaction(100,100.45);
Instead try like:
#define count 0.5
void transaction(int x, float acc_bal)
{
float z = acc_bal - count - x; // z will be new balance if the transaction is made
if (z >= 0 && x % 5 == 0) // check if the transaction can be made
{
acc_bal = z; // it could... so update balance
}
printf("%0.2f\n",acc_bal); // print current balance
}
int main(void)
{
transaction(100,100.45); // not ok - can't pay bank charges
transaction(99, 100.45); // not ok - x is not a multiple of 5
transaction(95, 100.55); // ok
}
Output:
100.45
100.45
5.05
The code in the question exhibits several deviations and potential deviations from the problem specification:
The program does not correctly test whether a transaction can be completed, because it tests whether the requested amount is less than the account balance instead of whether the requested amount plus the withdrawal fee is less than or equal to the balance.
It is not known that float has sufficient precision to represent the bank balance.
The program fails to end output lines with a newline character. (Although the problem statement does not state this explicitly, it may be expected implicitly.)
The program fails to include <stdio.h>.

Shipping calculator not returning correct results

The assignment is to write a shipping calculator using the following information.
Packages above 50 pounds will not be shipped. You need to write a program in C that calculates the shipping charge.
The shipping rates are based on per 500 miles shipped. They are not pro-rated, i.e., 600 miles is the same rate as 900 miles or 1000 miles.
Here are the shipping charges -
Package Weight Rate per 500 miles shipped
Less than or equal to 10 pounds $3.00
More than 10 pounds but less than or equal to 50 pounds $5.00
If the shipping distance is more than 1000 miles, there is an additional charge of $10 per package shipped.
I originally started writing the program using double but wanted to used a trick I had seen on here to always force the program to round up for the shipping charges by adding 499 to distance then dividing by 500.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int Shipping, packageWeight, packageDistance, packagePrice;
printf("Enter the weight of the package: \n");
scanf("%d", &packageWeight);
printf("The weight you have entered is %.2d\n", packageWeight);
if (packageWeight <= 10 )
Shipping = 3.00;
if (packageWeight <= 50 && packageWeight > 10 )
Shipping = 5.00;
if (packageWeight > 50.0) {
puts("Sorry, we only ship packages of 50 pounds or less.");
return 0;
}
printf("How far are you sending the package? \n");
scanf("%d", &packageDistance);
printf("The distance you entered is %.2d\n", packageDistance);
if (packageDistance <= 1000){
packagePrice = (packageDistance + 499 / 500) * Shipping;
printf("The shipping charge is %.2d \n", packagePrice);
system("pause");
}
if (packageDistance > 1000) {
packagePrice = (packageDistance + 499 / 500) * Shipping + 10.00;
printf("The shipping charge is %.2d \n", packagePrice);
system("PAUSE");
}
}
With a weight of 10 and distance of 501 the output should be a shipping charge of 6 but was 1503
Based on a a weight of 20 and a distance of 1001 the program should output a shipping charge of 25 but was 5000
You have mess with integers / doubles, output, expressions, etc.
Let me show you why you get 1503:
if (packageDistance <= 1000){
packagePrice = (packageDistance + 499 / 500) * Shipping;
printf("The shipping charge is %.2d \n", packagePrice);
system("pause");
}
Your packageDistance is 501 then if statement is true and you get inside.
Then you setup package price. First you get packageDistance which is 501. Then you add it with 499/500 which is 0 since 499 < 500 and you attempt to get integer part of division (as per C/C++ standard). The sum of 501 and 0 is 501.
Now, you multiply it with Shipping. The value you set is 3.0, but smart C convert it to integer 3. 501 * 3 is 1503 and you get the result.
Finally, you try to sent output as %.2d. This is nonsense and I am surprised C shows something at all, but I believe it just see d and ignores .2
This is what you have to do:
Understand your business logic (you do)
Be careful with integers and floating point numbers, read C documentation or send questions here if you do not understand something.
Make sure you use brackets when needed: a + b / c is not the same as (a + b) / c
Make sure you do not use integer division if you mean to use "regular" division.
Make sure you use %d for integers and %.2f for floating point numbers when appropriate.

How to stop a C while loop at once when we keyboard input without going on to the next step?

After I run this program, it has to stop when I input -999. But it stops even after the execution of -999. What have I done wrong here?
This was the question for the code.
Input employee number, and hours worked by employees, and to display the following:
Employee number, Over Time Payment, and the percentage of employees whose Over Time Payment exceeding the Rs. 4000/-.
The user should input –999 as employee number to end the program, and the normal Over Time Rate is Rs.150 per hour and Rs. 200 per hour for hours in excess of 40.
#include<stdio.h>
int main()
{
int empno=0,tot;
float hours, otp, prcn;
while(empno!=-999){
printf("Enter the Employee No: ");
scanf("%d",&empno);
printf("Enter the No of Hours: ");
scanf("%f",&hours);
if(hours<40){
otp=hours*150.00;
}
else
otp=((hours-40)*200)+(hours*150.00);
if(otp>4000){
prcn+=1;
tot+=1;
}
else
tot+=1;
printf("\nEmployee No: %d\n",empno);
printf("Over Time Payment: %.2f\n",otp);
printf("Percentage of Employees whose OTP exceeding the Rs. 4000/-: %.2f%%\n\n",(prcn/tot)*100);
}
}
I expect it to stop when I enter -999 without going on.
There is no statement after:
printf("Enter the Employee No: ");
scanf("%d",&empno);
and before:
printf("Enter the No of Hours: ");
scanf("%f",&hours);
that would cause your program to stop after you enter -999. The while loop check happens once when you start (before you enter the first employee number) but it doesn't happen again until after you do all the data entry, calculation and printing.

How to make a table in C using loops

How do you make a table like the pic (you are using the ideal gas law). The volume values should start on the left-most column with the start volume and increase in equal steps
such that the right-most column's volume is the stop volume. For each entry in the table, compute the pressure at the given temperature and volume, Please help.
Volume: 10.00 --- 18.89 --- 27.78 --- 36.67
Temp:
300.00 - 24.94 --- 13.20 --- 8.98 --- 6.80
400.00 - 33.26 --- 17.61 ---11.97--- 9.07
500.00 - 41.57 --- 22.01 ---14.97--- 11.34
#include <stdio.h>
int main(void)
{
float vol1, vol2;
float temp1, temp2;
float R = 8.314;
int mole;
int rows;
int columns = 8;
printf("Enter the starting volume (in meters cubed):");
scanf("%f",&vol1);
while(vol1<0)
{
printf("Error: Enter a number that is positive:");
scanf("%f",&vol1);
}
printf("Enter the ending volume (in meters cubed):");
scanf("%f",&vol2);
while(vol2<0)
{
printf("Error: Enter a number that is positive:");
scanf("%f",&vol2);
}
printf("Next enter the starting temperature (in kelvin):");
scanf("%f",&temp1);
while(temp1<0)
{
printf("Error: Enter a number that is positive:");
scanf("%f",&temp1);
}
printf("Enter the ending temperature (in kelvin):");
scanf("%f",&temp2);
while(temp2<0)
{
printf("Error: Enter a number that is positive:");
scanf("%f",&temp2);
}
printf("Enter the number of moles:");
scanf("%f",&mole);
while(mole<0)
{
printf("Error: Enter a number that is positive:");
scanf("%f",&mole);
}
printf("How many rows should the temperature value have?\n");
scanf("%d",&rows);
while(rows<1)
{
printf("Error: Enter a number that is positive:");
scanf("%d",&rows);
}
return 0;
}
I think I know what you're asking, so I'll reword your question so it is clear. You are trying to print out a 2D table with values that change in equal steps in the x direction (volume in this case) and equal values in the y direction (temperature in this case). I think that vol1 is starting volume and vol 2 is ending volume? and same for tmeperature?
The key to doing this is to use nested for loops
So something like this
for (x=vol1; x<vol2; x + volstepsize)
{
for(y=temp1; y<temp2; y + tempstepsize)
{
compute gas law equation here using x and y and do a print statement
}
perform a blank print line statement here to indent/start the next row
}
By having nested for loops you will print out row and column sequentially; this is a fundamental concept for accessing and writing 2D tables.
Hope that helps!

Too few arguments in function to call [C program]

So, I have an assignment due tomorrow night for my online C programming class, and I am having some problems with my coding at the moment. I have brought the code to my teacher, but she doesn't seem to understand that she is being paid to teach me, not tell me that something is wrong with my code. I would appreciate if someone could take a look at the code and help me fix it. Code is located below. The location where I get my error is in main when calling the printtripSummary.
#include <stdio.h>
void welcomeMessage();
void askuserForInput();
void printtripSummary(float avgMiles, float minCost, float maxCost, float travelMiles);
int main()
{
/* Call the functions */
welcomeMessage();
askuserForInput();
printtripSummary();
printf("\nThank you, please drive safely and have a nice trip!\n");
return 0;
}
void welcomeMessage()
{
printf("Welcome to the Trip Planner!\n");
printf("So you are ready to take a trip? Let me help you plan for\n");
printf("your fuels costs and required stops to fill up your tank.\n");
printf("============================================================\n");
printf("Please provide answers to the prompts below and I will\n");
printf("display a summary for you when I have computed the results.\n");
printf("============================================================\n");
}
void askuserForInput()
{
float avgMiles, minCost, maxCost, travelMiles;
do{
printf("Please input your car's average miles per gallon (enter 0 to quit)>> ");
scanf_s("%f", &avgMiles);
if (avgMiles == 0)
break;
printf("Please tell me the range of fuel costs you expect to pay (per gallon>>)\n");
printf("The lowest per gallon cost of fuel is>> ");
scanf_s("%f", &minCost);
printf("The highest per gallon cost of fuel is>> ");
scanf_s("%f", &maxCost);
printf("Please tell me how many miles you plan to travel>> ");
scanf_s("%f", &travelMiles);
printtripSummary(avgMiles, minCost, maxCost, travelMiles);
} while (avgMiles != 0);
}
void printtripSummary(float avgMiles, float minCost, float maxCost, float travelMiles)
{
float avgGal, mingasPrice, maxgasPrice;
do{
avgGal = travelMiles / avgMiles;
mingasPrice = avgGal * minCost;
maxgasPrice = avgGal * maxCost;
printf("You will be required to purchase %.2f gallons of fuel.\n", avgGal);
printf("The price will range between %2f and $%.2f.\n", mingasPrice, maxgasPrice);
} while (avgMiles != 0);
}
Comment out the function call in main like this (Line 13):
//printtripSummary();
Because you call the function already in askuserForInput(); and this function get called in main
OR if you want to call the function also in main your have to pass the required arguments which are:
(float avgMiles, float minCost, float maxCost, float travelMiles)
Also you have a endless loop in the function printtripSummary(); Because you have a do...while loop which checks if avgMiles != 0, but since your not changing the value of avgMiles in this loop it's endless!
On line 13 you're calling the printtripSummary function without passing any arguments to it. You have to provide the 4 arguments the function definition specifies (avgMiles, minCost, maxCost, travelMiles).

Resources