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.
Related
I have written a code for a ticket reservation halfway and I'm doubtful about the way i have used structures and arrays in my code. This code is not formatted properly because I am trying to see if this method of declaring "Bill" type variable will work or is this wrong?
the code gets compiled and runs successfully but I am doubtful whether my method is correct. Can anyone help? I just want to know whether the way I have declared structure type variables and used it is correct?Especially the last printf statement where I calculate the Amount.
#include<stdio.h>
#include<string.h>
#define SIZE 3
typedef struct
{
int billno;
char name[20];
char cat[20];
int type;
int range[3];
int tickets;
int class[3];
float price;
}Bill;
int main()
{
Bill array[3];
Bill d;
int input;
array[0].billno=6434;
strcpy(array[0].name,"Nimal");
strcpy(array[0].cat,"General");
array[0].type=1;
array[0].range[0]= 250;
array[0].range[1]= 0;
array[0].range[2]= 0;
array[0].price = 200;
array[1].billno=6065;
strcpy(array[1].name,"Kamal");
strcpy(array[1].cat,"Industrial");
array[1].type=2;
array[1].range[0]=622;
array[1].range[1]=1999;
array[1].range[2]=102;
array[1].price =125.60;
array[2].billno=7067;
strcpy(array[2].name,"Gayani");
strcpy(array[2].cat,"General");
array[2].type=2;
array[2].range[0]=220;
array[2].range[1]=350;
array[2].range[2]=10;
array[2].price = 86.90;
printf("****Main Menu****");
printf("1.Reserve a ticket:");
scanf("%d",&input);
if(input == 1)
{
printf("Enter your name: ");
scanf("%s", d.name);
printf("Enter the number of tickets you want");
scanf("%d",&d.tickets);
printf("Enter the number of tickets from first class");
scanf("%d",&d.class[0]);
printf("Enter the number of tcikets from second class");
scanf("%d",&d.class[1]);
printf("Enter the number of tickets from third class");
scanf("%d",&d.class[2]);
}
printf("\nReserve a ticket");
printf("\nName : %s",d.name);
printf("\nTickets from first class : %d",d.class[0]);
printf("Tickets from second class : %d\n",d.class[1]);
printf("Tickets from third class : %d\n",d.class[2]);
printf("\nConfirm the order? press Y if yes : ");
printf("Amount = %.2f ",d.class[0]*array[0].price+d.class[1]*array[1].price+d.class[2]*array[2].price);
return 0;
}
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 currently working to make an indexer for the students score, but, since I am new in C, I dont get the grasp of reading errors. Here's the error I have:
c:11:27: error: expected ‘;’, ‘,’ or ‘)’ before ‘.’ token
11 | double average(float input.score, int input.many){
c:34:13: warning: comparison between pointer and integer
34 | for(i=0; i < nas->many; i++){
c:48:3: warning: implicit declaration of function ‘average’ [-Wimplicit-function-declaration]
48 | average(sum, nas->many);
The while loop won't work properly
This is the code I work on:
#include <stdio.h>
#include <string.h>
#define MAX 100
typedef struct{
float score, avg, sum, *many;
char name[100][100];
} input;
double average(float input.score, int input.many){
float sum=0, average, a;
int i;
for(i=0; i<input.many;i++){
sum += input[i].score;
}
a = sum/input.many;
average=a;
return average;
}
int main(){
input nas[MAX];
float sum;
int choose, i, aa;
printf("How many students do you want to input?\n");
scanf(" %d",&nas->many);
for(i=0; i < nas->many; i++){
input nas[i];
printf("\nName of Student-%d\t\t: ",i+1);
scanf(" %[^\n]s", nas[i].name);
printf("The score of Student-%d\t\t: ",i+1);
scanf(" %f", &nas[i].score);
while(nas[i].score > 100 && nas[i].score < 0){
printf("Invalid! Please re-input the score\t\t: ");
scanf(" %f",&nas[i].score);
}
average(sum, nas->many);
}
printf("1--> Average of the scores");
scanf("%d", &choose);
if(choose == 1){
printf("The average of %d students is %f", nas->many, average());
}
...
else{ return 0;}
Can anybody help me to understand it? Thank you very much
Because you mustn’t use . inside a C identifier. It’s not valid. You could for instance replace it with _.
The only valid characters in a C identifier are letters, digits and underscore (ignoring Unicode).
So, you have some variables on struct thats do not make any sens, and you have some errors by send the parameters to the function and calling the function! You want the average of N students so you only can call the function after the insertion of score!
Other thing is why you need to save on every student, the sum of scores of all students, as the average of all students! And you are declaring the function always on for so when you insert for 1 student when loops back you lost your data because you declares it again!
#include <stdio.h>
#include <string.h>
#define MAX 100
typedef struct{
float score;
char name[100];
} input;
float average(input nas[], int many){
float sum=0, a;
int i;
for(i=0; i< many;i++){
sum += nas[i].score;
}
a = sum / many;
return a;
}
int main(){
input nas[MAX];
float sum;
int choose, i, many;
printf("How many students do you want to input: ");
scanf(" %d", &many);
for(i=0; i < many; i++){
printf("\nName of Student (%d): ",i+1);
scanf("%[^\n]s", nas[i].name);
printf("The score of Student (%d): ",i+1);
scanf("%f", &nas[i].score);
while(nas[i].score > 100 && nas[i].score < 0){
printf("Invalid! Please re-input the score: ");
scanf("%f", &nas[i].score);
}
}
sum = average(nas, many);
printf("\n1--> Average of the scores: ");
scanf("%d", &choose);
if(choose == 1){
for(int j=0; j < many; j++){
printf("\nName of Student: %s | Score: %f", nas[j].name, nas[j].score);
}
printf("\n\nThe average of %d students is %f\n", many, sum);
}
else{
return 0;
}
}
regarding:
scanf("%[^\n]s", nas[i].name);
are you expecting the user entered field name to be followed by a '\n' then a s?
Probably not.
Also, this statement does not remove the '\n' from stdin.
Therefore, IF anything, that s should be replaced with a space (so any trailing 'white space' is consumed. However, that is 'always' a bad idea.)
Strongly suggest using:
scanf("%[^\n]", nas[i].name); // note: no trailing `s`
note the next call to scanf() with a %f specifier will consume any leading 'white space'.
regarding:
scanf(" %d",&nas->many);
This may result in the first element in the array nas[] field many being set, but a much better method is:
scanf(" %d",&nas[0]->many);
regarding: right after the for() statement:
input nas[i];
This is declaring/re-declaring a new array with however many elements the i variable indicates. Probably not what you want to do.
regarding:
char name[100][100];
This is declaring a 2 dimensional array of 100 entries, with each entry being 100 characters. However, when ever the posted code references this 2d array, all that is given is name. The result will be all names will overlay each other in the first [0] entry
regarding:
scanf("%[^\n]s", nas[i].name);
besides the previously mentioned problem with the format string, and with using name without any indexing, the specifier: %[\n] does not limit the length of a name. Suggest:
scanf("%99[^\n]", nas[i].name[i]);
There are LOTS of other problems in the posted code besides those mentioned above.
I am revising my basic C to prepare for the upcoming quiz, when i was writing a function to simply take a character input and store it into a struct and print it out again. There is no issue with the compiling whatsoever but i kept getting logical issue. How do i fix this?
#include <stdio.h>
struct player
{
char letter;
int age;
double avg;
};
int main()
{
struct player P1;
char name;
int age;
double avg;
printf("Enter age: ");
scanf("%d", &age);
printf("Enter avg: ");
scanf("%lf", &avg);
printf("Enter name: ");
scanf("%s", &name);
P1.letter= name;
P1.avg = avg;
P1.age = age;
printf("\n Age is: %d \n", P1.age);
printf("Avg is: %lf", P1.avg);
printf(" \n Name is: %c \n", P1.letter);
return 0;
}
If i put in '1' for int, output would be "Age is: 0'
you are trying to get name, age and avg. of the player. so to store name , you should declare an array not a character. and for assigning the name to structure variable use strcpy().(direct assignment not works). OR if you taking only a single character as a name then write scanf like this:
scanf("%c", &name);
check below code, it will help you,
#include <stdio.h>
struct player
{
char letter[10];
int age;
double avg;
};
int main()
{
struct player P1;
char name[10];
int age;
double avg;
printf("Enter age: ");
scanf("%d", &age);
printf("Enter avg: ");
scanf("%lf", &avg);
printf("Enter name: ");
scanf("%s", &name);
strcpy(P1.letter,name);
P1.avg = avg;
P1.age = age;
printf("\n Age is: %d \n", P1.age);
printf("Avg is: %lf", P1.avg);
printf(" \n Name is: %s \n", P1.letter);
return 0;
}
You are using a character data type for entering a string, "char name" which is leading you to undefined behavior.
Instead of that you declare a character array like this "char name[10]" and then read name. but while assigning you have to take care that you can not assign directly you have to use strcpy like this.
strcpy(p1.letter,name) (Here letter is also character array)
Two quick suggestions:
1) Unless you are certain the name buffer will be populated only by short names, (9 or less characters), pick a more reasonable size for the buffer, such as:
char name[100];
This will also require lengthening the member letter in your struct.
2) when using scanf() to read in variables, the address of the variable being read is passed as the 2nd argument. For variables such as int a; or float b; you must use the address of operator: & as a prefix to the variable. But because the variable name of a C string points to the first character in the array, it already is the address of that variable. So you do not need the explicit & operator when reading a C string into the scanf() function. The return value of the function should also be used to determine if the call was successful. Change the following line as shown:
scanf("%s", &name);
int count = scanf("%s", name);//note: use return value of function
// remove & ^
if(count < 0)
{
//handle error
}
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