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;
}
Related
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
I created a function called average that will calculate the average age. How ever it is generating a strange negative decimal point.It was working fine until I put the strcmp function to people who have enter Texas. Example ages: 20 50 20 30 & 40 generate The average age is -243454739.00.
Can someone point me in the right direction, Thanks.
#include <stdio.h>
#include <string.h>
int main()
{
//function decleration
float average ( int A, int n);
//int deleceration
char names, states, statedata[100], namedata[100];
int agedata[100], age, count = 0, A, n, avg;
float a;
//Get User Input
printf("Enter Number of family members being enter into program \n");
scanf("%d", &n);
//Name Loop
for (names=0; names<n; ++names)
{
printf("Enter Family members name:\n");
scanf("%s", &namedata);
//Age Loop
for (age=0; age<1; ++age)
{
printf("Enter family members age:\n");
scanf("%d", &agedata[age]);
A +=agedata[age];
count= count + 1;
//State Loop
for (states=0; states<1; ++states)
{
printf("Enter Family members state:\n");
scanf("%s", &statedata);
//strcmp function for state name "Texas" Selection
if (strcmp(statedata,"texas")==0)
{
printf("Family members who live in texas\n");
printf("%s\n", namedata);
}
}
}
}
// Average function call
a = average(A, n);
printf("The average age is %.2f\n", a);
return 0;
}
//A declarator
float average( int A, int n){
float average;
average = A / n;
return average;
}
Initialize A to 0 in main(). Uninitialized local variables have indeterminate values in C.
Other issues:
1)
scanf("%s", &namedata);
scanf("%s", &statedata);
Shoud be
scanf("%s", namedata);
scanf("%s", statedata);
Because scanf() expects a char* when for format specifier %s whereas you are passing char(*)[100].
2)
All the values of ages are using type int. So the having the function average() return a float is still going to give an int result.
Change the type A (in main()) and the function parameter A (in average()) to float.
3)
Your inners are running 0..1 i.e. only once. So you don't really need those loops.
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;
}
}
}
My friend and I are trying to build a program together, but it just doesn't seem to be working. Neither of us have much experience with C, so we just can't spot the issue... Any advice or help would be much appreciated!
Apologies for the slightly awkward lyrics?
[Edit] The problem is that when we input values, we get ridiculous figures like 4586368.
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
void main()
{
int room[20] = {};
int i;
int rooms = 0;
char option = 0;
int lights = 0;
int hrsUsed = 0;
int Telly = 0;
int TVWatt =0;
int sumTV;
int TVuse = 0;
int Computer = 0;
int compWatt = 0;
int compUsed = 0;
int compTotal;
int kwH_lights;
int fridge = 0;
int washLoad = 0;
int dryerLoad = 0, dishLoad = 0, cookLoad = 0;
int showeruse = 0;
int total_kWh;
printf("Enter number of rooms");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++)
{
printf("input average wattage of lights");
scanf_s("%d", &lights);
lights=lights/1000;
printf("input number of hours use/day (average)");
scanf_s("%d", &hrsUsed);
kwH_lights=((lights*hrsUsed)*365);
printf("input number of TVs");
scanf_s("%d", &Telly);
printf("input average wattage");
scanf_s("%d", &TVWatt);
printf("input average use a day");
scanf_s("%d", &TVuse);
sumTV=((Telly*(TVWatt/1000))*TVuse)*365;
}
printf("Input number of fridge/freezer");
scanf_s("%d",&fridge);
fridge=(fridge*2)*365;
printf("input number of Computers and/or video game consoles in the house");
scanf_s("%d", &Computer);
for(i=0;i<Computer;i++) {
printf("input wattage");
scanf_s("%d", &compWatt);
printf("input average hrs used/day");
scanf_s("%d", &compUsed);
compTotal=((compWatt/1000)*compUsed)*365;
}
printf("Input average number of washing machine loads /day");
scanf_s("%d",&washLoad);
washLoad=washLoad*365;
printf("Input average number of clothes dryer loads/day");
scanf_s("%d",&dryerLoad);
dryerLoad=(dryerLoad*3)*365;
printf("Input average number of dishwasher loads/day");
scanf_s("%d",&dishLoad);
dishLoad=(dishLoad*1.5)*365;
printf("Input average cooking load/day");
scanf_s("%d",&cookLoad);
cookLoad=(cookLoad*7)*365;
printf("Input average hrs/day of shower usage");
scanf_s("%d",&showeruse);
showeruse=(showeruse*7)*365;
total_kWh=((kwH_lights)+(sumTV)+(fridge)+(compTotal)+(dryerLoad)+(dishLoad)+(cookLoad)+(showeruse));
printf("Total= %d", &total_kWh);
}
You should change this:
printf("Total= %d", &total_kWh);
to that:
printf("Total= %d", total_kWh);
Same is true for all your other integer variables.
There were quite a few mistakes in your code:
you printed the memory-address instead of result value (don't use & with printf if your variable is a plain int)
the computer for-loop had no curly brackets (so only the printf statement was looped)
results were not summed up (in all loops you've just overwritten your inputs from the last loop)
the rooms[] Array was never used - a few other variables also (possible error source, if you wanted to use them and just forgot it)
the result from a multiplication with 1.5 will hold a double value - you should cast that back to int (dishLoad)
The bold mistake is probably that one, why your values were wrong...
Also notice: The 'average number of washing machine loads/clothes dryer loads/ dishwasher loads' should better be asked by week or month... Or should hold Floating Point values: Because everyone I know don't use the washing machine and clothes dryer every day multiple times. So now you can't enter something like once a week (which would be an factor of 0.14, but is not enterable cause all values are stored as int).
Here Comes the code with everything fixed, I could found:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int main(int argc, char** argv){
int i = 0;
int rooms = 0;
int lights = 0;
int hrsUsed = 0;
int Telly = 0;
int TVWatt =0;
int sumTV = 0;
int TVuse = 0;
int Computer = 0;
int compWatt = 0;
int compUsed = 0;
int compTotal= 0;
int kwH_lights = 0;
int fridge = 0;
int washLoad = 0;
int dryerLoad = 0, dishLoad = 0, cookLoad = 0;
int showeruse = 0;
int total_kWh = 0;
printf("Enter number of rooms: ");
scanf_s("%d", &rooms);
for(i=0;i<rooms;i++){
printf("A few questions about room %d\n", i+1);
printf("input average wattage of lights: ");
scanf_s("%d", &lights);
lights+=lights/1000;
printf("input number of hours use/day (average): ");
scanf_s("%d", &hrsUsed);
kwH_lights+=((lights*hrsUsed)*365);
printf("input number of TVs: ");
scanf_s("%d", &Telly);
printf("input average wattage: ");
scanf_s("%d", &TVWatt);
printf("input average use a day: ");
scanf_s("%d", &TVuse);
sumTV+=((Telly*(TVWatt/1000))*TVuse)*365;
}
printf("Input number of fridge/freezer: ");
scanf_s("%d",&fridge);
fridge=(fridge*2)*365;
printf("input number of Computers and/or video game consoles in the house: ");
scanf_s("%d", &Computer);
for(i=0;i<Computer;i++){
printf("A few questions about computer %d\n", i+1);
printf("input wattage: ");
scanf_s("%d", &compWatt);
printf("input average hrs used/day: ");
scanf_s("%d", &compUsed);
compTotal += ((compWatt/1000)*compUsed)*365;
}
printf("Input average number of washing machine loads/day: ");
scanf_s("%d",&washLoad);
washLoad=washLoad*365;
printf("Input average number of clothes dryer loads/day: ");
scanf_s("%d",&dryerLoad);
dryerLoad=(dryerLoad*3)*365;
printf("Input average number of dishwasher loads/day: ");
scanf_s("%d",&dishLoad);
dishLoad=(int)((dishLoad*1.5)*365);
printf("Input average cooking load/day: ");
scanf_s("%d",&cookLoad);
cookLoad=(cookLoad*7)*365;
printf("Input average hrs/day of shower usage: ");
scanf_s("%d",&showeruse);
showeruse=(showeruse*7)*365;
total_kWh=((kwH_lights)+(sumTV)+(fridge)+(compTotal)+(dryerLoad)+(dishLoad)+(cookLoad)+(showeruse));
printf("Total= %d\n", total_kWh);
system("Pause");
return 0;
}
I hope it helps you out - if you got any questions left, feel free to ask.
My first step would be to correct the second for loop { } ... fix this and ask again.
[EDIT]
your calculations with usages of int values divided by other ints (compwatt / 1000) ... are you sure your idea of using int is correct?
or:
cookLoad=(cookLoad*7)*365;
why multiplying with 7 AND 365? should not the average / day be multiplied by 365 only?
For more readability of your code, you can employ compound assignment operators as below,
Operator Name Syntax Meaning
-------------------------------------------------
Addition assignment a += b a = a + b
Subtraction assignment a -= b a = a - b
Multiplication assignment a *= b a = a * b
Division assignment a /= b a = a / b
I tried to search this everywhere, but it's kind of difficult to word, it's most likely a simple fix. Basically when I go through my program that is supposed to compute the average rainfall for a year, it comes out with a very large number, however, I thought it may have been just that I was doing the arithmetic wrong or had a syntax error of some sort, but that was not the case, when I checked the value that the function returned it was the proper value.
#include <stdio.h>
#include <string.h>
void getData(float *, float *);
int main()
{
char state[2], city[81];
float rainFall[12], outputAverage, *pAverage;
printf("Name Here\n");
printf("Please enter the state using a two letter abreviation: ");
gets(state);
printf("Please enter the city : ");
gets(city);
pAverage = &outputAverage;
(getData(rainFall, pAverage));
printf("%.2f", outputAverage);
return (0);
}
void getData(float *rainFall, float *pAverage)
{
int i;
float total;
for (i=0; i<12; i++)
{
printf("Please enter the total rainfall in inches for month %d: ", i+1);
scanf("%f", &rainFall[i]);
total += rainFall[i];
}
*pAverage = total / 12;
}
you need to initialize total
float total = 0.0;
Initialize the total to 0
Why you make it complicated? Why not just
return total / 12 ?
and called it like
outputAverage = getData(rainfall)
This is a classic problem in C programming. You are mixing strings and numbers on the input. You are better off reading the input into a string and then, using sscanf to parse it properly.
You have uninitialized variable total which is taking garbage value, thus you see a very large answer.
changed your main.. have a look and let me know if you have understood what changes i have made?
#include <stdio.h>
#include <string.h>
void getData(float *);
int main(int argc, char*argv[])
{
char state[3]={0}, city[81]={0};
float outputAverage;
printf("Name Here\nPlease enter the state using a two letter abreviation: ");
scanf("%s",state);
printf("Please enter the city : ");
scanf("%s",city);
getData(&outputAverage);
printf("The Average Rainfall recorded for the year is %.2f\n", outputAverage);
return 0;
}
void getData(float *pAverage)
{
int i;
float rainFall[12]={0}, total=0;
for (i=0; i<12; i++)
{
printf("Please enter the total rainfall in inches for month %d: ", i+1);
scanf("%f", &rainFall[i]);
total += rainFall[i];
}
*pAverage = total / 12;
}
However instead of using gets you should use fgets but i forgot how to counter the issue of using simultaneous fgets to read input from the standard input stream.
Also initialize the total variable as you are adding in the loop new values to existing value in that variable which would not necessarily add to zero as the premier element. so it could be any garbage value + loop values.
I understand you are practicing pointer concept so you passed the address of the array of floats to your second function but if the rainfall function is not useful in main, Better to restrict the same where it would be useful