我运行此代码并在数组'中输入浮点值。但排序后,数组元素的新值与输入值略有不同。为什么会这样? 这是我运行的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <conio.h>
void main()
{
int N,sorted,i;
printf("How many students?\n");
scanf("%d",&N);
float s[N],temp;
for(i=0;i<N;i++)
{
printf("Marks of student %d?\n",i+1);
scanf("%f",&s[i]);
}
//bubble sorting ---
while(1)
{
sorted=0;
for(i=0;i<N-1;i++)
{
if(s[i]<s[i+1])
{
temp=s[i];
s[i]=s[i+1];
s[i+1]=temp;
sorted=1;
}
}
if(sorted==0)
break;
}
printf("\nSorted Marks - \n\n");
for(i=0;i<N;i++)
{
printf("%f\n",s[i]);
}
}
输入:
N=5
Marks = 34.53,54,34,56.76,87.567
输出:
Sorted Marks -
87.567001
56.759998
54.000000
34.529999
34.000000
答案 0 :(得分:0)
简短的回答是并非所有浮点数都可以精确存储,因此系统选择“最接近”的可能数字,这可能导致例如34.53
正在追问34.529999
。
- 一些程序员老兄
您可以通过两种方式“解决”问题。 1)将float
更改为double
,将"%f"
更改为"%lf"
中的scanf
。 2)将"%f"
更改为"%.4f"
中的printf
。
- user3386109