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
Related
I'm writing some code to calculate GPA and when I start a loop, one of my variables "numClasses" changes value to a huge number midway through the loop and I can't figure out what's going on.
#include <stdio.h>
int main()
{
float crdtHrs[] = {}; //Credit hours for this term
float numClasses; //Amount of classes taken this term
float qltyPoints[] = {}; //Quality points for term
float classes[] = {}; //Array for class grades
printf("Please enter total number of classes -> ");
scanf("%f", &numClasses);
float a = numClasses; //using new variable because this way the loop works
for(int i = 1; i <= a; i++)
{
printf("\nGPA class #%d -> ", i);
scanf("%f", &classes[i - 1]);
printf("Credit hours for course -> ");
scanf("%f", &crdtHrs[i - 1]);
printf("%f", numClasses); //at some point of my loop numClasses changes value
}
return(0);
}
Nice zero length array buffer overrun. Boom. Let's arrange so the arrays are declared a little later so we can give them sizes.
printf("Please enter total number of classes -> ");
scanf("%f", &numClasses);
int a = (int)numClasses;
float crdtHrs[a]; //Credit hours for this term
float qltyPoints[a]; //Quality points for term
float classes[a]; //Array for class grades
Now we allocate the arrays on the stack at the right size.
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;
}
// 6.1 Brain Teaser
#include <stdio.h>
int pills,weight;
float bottlenumber;
void load ()
{
printf("Enter the number of pills: ");
scanf("%d", &pills);
printf("Enter the weight of your pills: ");
scanf("%d", &weight);
}
void calc ()
{
bottlenumber = (weight - 210) / (float)0.1;
}
void print()
{
printf("The bottle number is %.f!", bottlenumber);
}
void main()
{
load();
calc();
print();
}
The user is suppose to enter 211.3. The answer then is suppose to be 13 but instead I get 10. I think it has to do with float aspect and the calculation part.
weight is an int, not a float, and you're reading it in a as an int, so if the user enters 211.3 then weight contains 211.
If you expect weight to be a float then you should declare it as such and read it in as such.
float weight;
...
printf("Enter the weight of your pills: ");
scanf("%f", &weight);
this line is the problem:
bottlenumber = (weight - 210) / (float)0.1;
remember, the value entered for weight is 3.
so 3 - 210 = -207
next divide -207 by 0.1 which = -2070
I suspect the line should be written somewhat differently
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.
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