Anyone knows why it din work

I try to write a code for sales and profit. profit is 10 percent of sales. and sales is 10 million . Every year, it lose 4 percent of its sales and show the next 10 years of sales and profit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 #include <stdio.h>
int main ()
{
	int year;
	float sales =10000000;
	float profit;
	profit=sales*10/100;
	printf("The sales is %.2f and profit is %.2f\n\n",sales, profit);
	for (year=1;year<=10;year++)
	{
		sales =sales- 4/100*sales;
		
		printf("The %d year\t Sales:%.2f\tProfit:%.2f\n",year,sales,profit);
		
	}
}
I don't know C that well, tough i assume this is what you wanted
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
int main ()
{
	int year;
	float sales =10000000;
	float profit;
	printf("The sales is %.2f and profit is %.2f\n\n",sales, profit);
	for (year=1;year<=10;year++)
	{
        profit=sales/10;
		sales =sales- 4*sales/100;
		printf("The %d year\t Sales:%.2f\tProfit:%.2f\n",year,sales,profit);

	}
}
Well you did not change much. The problem is the code result is not what it is decreasing. It show 10 millions for all repeat.
I try another way and it works but i still dun know why
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
int main ()
{
	int year;
	float sales =10000000;
	float profit=1000000;
	
	printf("The sales is %.2f and profit is %.2f\n\n",sales, profit);
	for (year=1;year<=10;year++)
	{
		sales =sales- sales*4/100;
		profit=sales*10/100;
		
		printf("The %d year\t Sales:%.2f\tProfit:%.2f\n",year,sales,profit);
		
	}
}

I change the 4/100*sales into sales*4/100. Then it works out of sudden. Anyone knows why.
You have integer division.

This line is ok (just) profit=sales*10/100;

But this causes a problem:
 
    sales =sales- 4/100*sales;

When evaluating the expression 4/100*sales, it proceeds from left to right. First divide 4 by 100, giving zero. (remember, those are integers). Next, multiply 0 by sales again giving zero.

It's best, unless you specifically want integers (it is ok for the loop counter year), use a decimal point to make the numbers a floating-point type.
 
    sales = sales - 4.0/100.0 * sales;


Also, you need to calculate the profit inside the loop too, for each year.


Let's go back and look at this line again sales*10/100. Because the calculation proceeds from left to right, sales*10 is done first. Sales is type float, so the result is float too. The same with the divide by 100 here. But it is less dangerous to not depend on the order of operations, use sales*10.0/100.0 or more simply sales*0.1.
Last edited on
Ya, you are right, integer division that cause the problem. Thanks a lot. Smart kids.
Topic archived. No new replies allowed.