I use bubble sort to 1.00 20.00 3.30 4.50 5.20 6.10 7.80 8.10 9.14 0.67
and i end up with
0.00 1.00 3.00 4.00 5.00 6.00 7.00 8.00 9.00 20.00
This is my code
main()
{
int i,n = 10,j,value=0;
float median=0;
float a[10] = {1,20,3.3,4.5,5.2,6.1,7.8,8.1,9.14,0.67};
for(i= 0; i< 10; i++) {
printf("%.2f ", a[i]);
}
printf("\n\n");
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(a[j]>a[j+1])
{
value=a[j+1];
a[j+1]=a[j];
a[j]=value;
}
}
}
for(i= 0; i< 10; i++) {
printf("%.2f ", a[i]);
}
}
Can anyone tell me what I am doing wrong and why I am losing all the digits after the decimal point when I am done with the sort.
PS I am using an online compiler http://www.compileonline.com/compile_c_online.php .
value
is an int
not float
.
int i,n = 10,j,value=0;
You get truncated values here in the loop:
value=a[j+1];
a[j+1]=a[j];
a[j]=value;
Make it float value=0.0f;
Problem is here:
int value=0;
Change to:
float value=0.0f;
您已将value
声明为int
Can anyone tell me what I am doing wrong and why I am losing all the digits after the decimal point when I am done with the sort.
You declared value
as an int
. value=a[j+1];
statement will truncate the value of a[j+1]
(which is of float
type) to int
. Declare value
as float
.
float value = 0.0f;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.