**C programming** For some reason I keep getting 0 for total profit and I dont r
ID: 3840765 • Letter: #
Question
**C programming** For some reason I keep getting 0 for total profit and I dont really know why.. Any help would be appreciated
struct tax
{
char name[15];
float sharenum;
float buyp,currp;
float buyc,currc;
float profit,totprofit;
};
void main()
{
struct tax s[size];
load(s, size);
}
void load(struct tax s[], int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Enter stock name: ");
gets(s[i].name);
printf("Enter the number of shares: ");
scanf("%f",&s[i].sharenum);
printf("Enter the buy price: ");
scanf("%f", &s[i].buyp);
printf("Enter the current price: ");
scanf("%f", &s[i].currp);
printf("=============================== ");
printf("=============================== ");
s[i].buyc=s[i].sharenum*s[i].buyp;
printf("The buying cost is: %0.2f ", s[i].buyc);
s[i].currc=s[i].sharenum*s[i].currp;
printf("The current cost is: %0.2f ", s[i].currc);
s[i].profit=s[i].currc-s[i].buyc;
printf("The profit is: %0.2f ", s[i].profit);
s[i].totprofit=s[i].totprofit+s[i].profit;
printf(" ");
printf(" ");
fflush(stdin);
}
printf("The total profit is: %0.2f", s[i].totprofit);
}
Explanation / Answer
Answer:
The issue in your code is you are trying to print the total profit after executing the for loop but storing the totprofit in the structure variable. That is 'printf("The total profit is: %0.2f", s[i].totprofit);' this statement is after the loop. The code looks for s[i].totprofit but since the for loop is completed and the i value is n+1 and since there is no profit calculated for n+1 the value is always 0.
I hope you are trying to calculate totprofit by summing all the profits. So if that's the case you can have a look at the working code below:
#include <stdio.h>
struct tax
{
char name[15];
float sharenum;
float buyp,currp;
float buyc,currc;
float profit;
};
void load(struct tax s[], int n)
{
int i;
float totprofit;
for(i=0;i<n;i++)
{
printf("Enter stock name: ");
gets(s[i].name);
printf("Enter the number of shares: ");
scanf("%f",&s[i].sharenum);
printf("Enter the buy price: ");
scanf("%f", &s[i].buyp);
printf("Enter the current price: ");
scanf("%f", &s[i].currp);
printf("=============================== ");
printf("=============================== ");
s[i].buyc=s[i].sharenum*s[i].buyp;
printf("The buying cost is: %0.2f ", s[i].buyc);
s[i].currc=s[i].sharenum*s[i].currp;
printf("The current cost is: %0.2f ", s[i].currc);
s[i].profit=s[i].currc-s[i].buyc;
printf("The profit is: %0.2f ", s[i].profit);
totprofit=totprofit+s[i].profit;
printf(" ");
printf(" ");
fflush(stdin);
}
printf("The total profit is: %0.2f", totprofit);
}
int main()
{
struct tax s[200];
load(s, 2);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.