When I run this code I expect the return give me (100-percent)/100 - price
#include<stdio.h>
#include<cs50.h>
float discount(int prec , float pri);
int main (void){
int percent = get_float("enter the present here ");
float price = get_float("enter the price ");
float function1 = discount(percent , price);
printf("the new number is %.2f\n", function1);
}
float discount(int prec , float pri){
return (100 - prec)/100 * pri ;
}
but I got this return and I don't know what the problem is
$ make lesson
$ ./lesson
enter the present here 15
enter the price 100
the new number is 0.00
when I use this code
#include<stdio.h>
#include<cs50.h>
float discount(int prec , float pri);
int main (void){
int percent = get_float("enter the present here ");
float price = get_float("enter the price ");
float function1 = discount(percent , price);
printf("the new number is %.2f\n", function1);
}
float discount(int prec , float pri){
return pri * (100 - prec)/100 ;
}
I got the correct value but I want to know why the first example didn't work
$ make lesson
$ ./lesson
enter the present here 14
enter the price 100
the new number is 86.00
Related
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;
}
I'm new at this and having some trouble. I'm trying to find the average of the grades that are inputed by the user but I realized that if you use a decimal in any of the grades, it's just being calculated as if they are whole numbers.
#include <stdio.h>
int main(void)
{
unsigned int counter;
float grade;
int total;
float average;
int number;
total = 0;
counter = 1;
printf("Number of scores to enter:\t");
scanf("%d", &number);
printf("\n");
while (counter <= number) {
printf("%s%d%s", "Enter the score for Lab ", counter, ":\t");
scanf("%f", &grade);
total = total + grade;
counter = counter + 1;
}
printf("\n");
average = (float) total / number;
printf("Average lab score: %.1f\n", average);
if (grade>=90) {
puts("Letter grade: A");
}
else if (grade>=80) {
puts("Letter grade: B");
}
else if (grade>=70) {
puts("Letter grade: C");
}
else if (grade>=60) {
puts("Letter grade: D");
}
else {
puts("Letter grade: F");
}
return 0;
}
You are capturing scanf("%f", &grade); as a float and then calculating total = total + grade;.
You have defined int total;. You would need to define it as float total;.
You are moving a float variable into an integer which is truncating the decimals you had previously entered.
There's no need to ask up front how many data points will be entered. Indeed, that is an anti-pattern. Just do something like:
#include <stdio.h>
int
main(void)
{
unsigned int count = 0;
float grade;
float total = 0.0;
float average;
while( scanf("%f", &grade) == 1 ) {
total += grade;
count += 1;
}
average = total / (float) count;
printf("Average lab score: %.1f\n", average);
fputs("Letter grade: ", stdout);
putchar( average >= 90.0 ? 'A' : average >= 80.0 ? 'B' :
average >= 70.0 ? 'C' : average >= 60.0 ? 'D' : 'F');
putchar('\n');
return average >= 60.0;
}
$ echo 78.2 96.5 80 | ./a.out
Average lab score: 84.9
Letter grade: B
Key points: total needs to be a float type. You must check the value returned by scanf. Always. Probably you want to handle bad input more cleanly that this does. This just throws away all data after an error and computes the average based on whatever data was entered prior to the error. A cleaner solution would abort with an error message. Exercise left for the reader.
A reasonable argument can be made that this is an abuse of the ternary operator; however you want to refactor it, don't repeat yourself by hardcoding the string "Letter grade: " multiple times.
Rather than abusing the ternary operator as above, you may prefer something like:
#include <stdio.h>
int
main(void)
{
unsigned int count = 0;
float grade;
float total = 0.0;
float average;
while( scanf("%f", &grade) == 1 ) {
total += grade;
count += 1;
}
average = total / (float) count;
int s = 'A' + (99 - (int)average) / 10;
printf("Average lab score: %.1f\n", average);
printf("Letter grade: %c\n", s > 'D' ? 'F' : s);
return average >= 60.0;
}
I am very new to C and am struggling with this code. I need to get the feet and inches of two athletes from user input using a structure, then total the inches of each athlete to determine the winner. The issue I'm having is that the value being returned doesn't make any sense. My guess is it has something to do with getting the address of the value instead of the actual value, but after changing some things around I just end up with errors or the program crashing. Any help is appreciated.
#include <stdio.h>
#include <stdlib.h>
//Distance Structure
struct Distance
{
int feet;
float inches;
};
int main() {
//Initialize athelete structures
struct Distance athlete1;
struct Distance athlete2;
//Get values for athlete 1
printf("Enter the distance for athlete 1\n");
printf("Feet: ");
scanf("%d", &athlete1.feet);
printf("Inches: ");
scanf("%d", &athlete1.inches);
//Get values for athlete 2
printf("Enter the distance for athlete 2\n");
printf("Feet: ");
scanf("%d", &athlete2.feet);
printf("Inches: ");
scanf("%d", &athlete2.inches);
//Convert values to inches
float total1 = calculateInches(athlete1.feet, athlete1.inches);
float total2 = calculateInches(athlete2.feet, athlete2.inches);
//Print distance in inches
printf("\nAthlete 1 has a distance of %d inches\n", total1);
printf("Athlete 2 has a distance of %d inches\n\n", total2);
//Print the winner
if(total1 > total2){
printf("Athlete 1 wins!");
}
else if(total1 < total2){
printf("Athlete 2 wins!");
}
else{
printf("Tie!");
}
return 0;
}
//Calculate Inches
int calculateInches(feet, inches){
float total;
total = (feet*12) + inches;
return total;
}
There are few issues with your code:
The format specifier to be used whenever you are using float is %f instead you are using %d
Try forward declaring your calculateInches() method. Write it above the main() method or try using a function prototype. have a look at this link
Mention the right types for the arguments to the function float calculateInches(float feet, int inches). Related question
Working example: https://ideone.com/jsMZgv
Can u guys help me how to make a simple report calculation
1st score x 20%
2nd score x 40%
3rd score x 40%
Sample :
Input :
65 56 100
Output :
75.00
My code :
#include <stdio.h>
#include <math.h>
int main() {
int score1, score2, score3;
float amount;
float n;
float percent1 = 0.2;
float percent2 = 0.4;
float percent3 = 0.4;
scanf("%f %f %f",&n, &n, &n);
score1 = (float)n*percent1;
score2 = (float)n*percent2;
score3 = (float)n*percent3;
amount = score1+score2+score3;
printf("%.2f\n", amount);
getchar();
return 0;
}
my input:
65 56 100
my output:
100.00
u can see it there, the output must be 92.00
is there any mistakes?
Help me pls, ty
You are using the same variable (n) for all three input values. You need a separate variable for each input value. Use the score variables to store the values and then use them in a single calculation.
#include <stdio.h>
#include <math.h>
int main()
{
int score1, score2, score3;
float amount;
/* Variable 'n' not required, since not used. */
float n;
float percent1 = 0.2;
float percent2 = 0.4;
float percent3 = 0.4;
scanf("%f %f %f",&score1, &score2, &score3);
amount = (score1 * percent1) + (score2 * percent2) + (score3 * percent3);
printf("%.2f\n", amount);
getchar();
return 0;
}
Good day! In a program I am writing for school we must make a cash register type program, seems simple enough, but for the life of me I can not get it to work. After taking in the number of products bought, then the price of all, the program must ask for the cash to pay, then give back the change. BUT the change must be given in amount of loonies back (or $1 bills), and then just the remaining cents. Help? I've gotten the loonies to work (somewhat) but I don't know how to do the change back.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int itemNum, justChange;
double prodPrice, tax, cashGiven, change, purchasePrice, changeGiven, changeBack, cashBack;
float totalPrice;
//Num of items
printf ("Number of items: ");
scanf("%d", &itemNum);
//Price of items
printf("Please enter price of items: ");
scanf("%lf", &prodPrice);
//Math Stuff
purchasePrice = itemNum*prodPrice;
tax = purchasePrice * 0.13;
totalPrice = purchasePrice*1.13;
//find change alone
//justChange = totalPrice
//Price Output
printf("Purchase price is: %.2lf \n",purchasePrice );
printf("TAX (HST 13%): %.2lf\n",tax );
printf("Total price is: %.2lf \n",totalPrice );
printf("Please Enter Cash: ");
scanf("%lf", &cashGiven);
printf("Please Enter Change: ");
scanf("%lf", &changeGiven);
//MAth stuuff again
double endCash;
double loony;
int yoloswag;
endCash = cashGiven - totalPrice;
loony = endCash/1;
loony = loony--;
if (loony<0)
printf ("Loonies: 0");
else
printf("Loonies: %.0lf \n",loony );
printf("change: %d ", totalPrice-floor(totalPrice) );
return 0;
}
Create an array with possible change values;
double cashValues[6] = {1, 0.5, 0.2, 0.1, 0.05, 0.01};
Then create a for loop in which you try to subtract the possible change values from the difference until the difference is zero.
double difference;
difference = cashGiven - totalPrice;
while (difference != 0) {
for(int i=0; i<6; i++) {
if(cashValues[i] <= difference) {
difference -= cashValues[i];
printf("%f \n", cashValues[i]);
i=0;
}
}
}