Objective c 被小于1的浮点除时为无穷大?
我有以下代码:Objective c 被小于1的浮点除时为无穷大?,objective-c,c,Objective C,C,我有以下代码: float f; float time; time=samplesPerPeriod/44; f=(1/time)*1000; 当SamplesPerPerPerPeriod为35时,我在该日志中得到无穷大: NSLog(@"frequency:%f Hz",f); 我不能除以一个比1小的数吗? 这和目标c类中的c函数有关吗 谢谢。您需要为线路使用浮点数 time=samplesPerPeriod/44; 因此,你应该这样做 time=(float
float f;
float time;
time=samplesPerPeriod/44;
f=(1/time)*1000;
当SamplesPerPerPerPeriod为35时,我在该日志中得到无穷大:
NSLog(@"frequency:%f Hz",f);
我不能除以一个比1小的数吗?
这和目标c类中的c函数有关吗
谢谢。您需要为线路使用浮点数
time=samplesPerPeriod/44;
因此,你应该这样做
time=(float)samplesPerPeriod/44.0;
如果samplesperperion
是一个int
,则该除法将是整数除法。这意味着你真的在做
35/40
作为
int
,它是0
,它是,然后转换为float
,值为0.0
。因此,您需要在除法之前将samplesperpoint
强制转换为浮点,为了安全和清晰,在分母中使用float
值44.0
。您需要对行使用浮点
time=samplesPerPeriod/44;
因此,你应该这样做
time=(float)samplesPerPeriod/44.0;
如果samplesperperion
是一个int
,则该除法将是整数除法。这意味着你真的在做
35/40
作为
int
,它是0
,它是,然后转换为float
,值为0.0
。因此,您需要在除法之前将samplesperperion
强制转换为浮点,为了安全和清晰,在分母中使用float
值44.0
。我假设samplesperperion
是整数类型。如果是,则在整数数学中执行samplesperperion/44
,因此结果为0。然后你做的是1/0.0,这是无穷大
要解决此问题,请执行以下任一操作:
time = (float)samplesPerPeriod / 44;
time = samplesPerPeriod / 44.0;
time = (float)samplesPerPeriod / 44.0;
我假设
samplesperperion
是一个整数类型。如果是,则在整数数学中执行samplesperperion/44
,因此结果为0。然后你做的是1/0.0,这是无穷大
要解决此问题,请执行以下任一操作:
time = (float)samplesPerPeriod / 44;
time = samplesPerPeriod / 44.0;
time = (float)samplesPerPeriod / 44.0;
var
SamplesPerPerPerPerPerPerPerPeriod
是哪种类型?我想int
。要正常工作,您的代码应该如下所示:
time = (float)samplesPerPeriod / 44.0;
var
SamplesPerPerPerPerPerPerPerPeriod
是哪种类型?我想int
。要正常工作,您的代码应该如下所示:
time = (float)samplesPerPeriod / 44.0;
35/44的结果为0.0,因为
- in case of = operator right side is evaluated first and assigned to left.
- 35/44 is 0. (as both are int)
so finally 1/0.0 results in infinite.
使用
35f/44f
,则它将被视为浮动35/44结果为0.0,因为
- in case of = operator right side is evaluated first and assigned to left.
- 35/44 is 0. (as both are int)
so finally 1/0.0 results in infinite.
使用
35f/44f
,则假定SamplesPerPerPerPerPerPeriod
为整数类型,则它将被视为浮点数
float time;
time = samplesPerPeriod / 44;
然后,/运算符的两个操作数都是整数类型,并执行整数除法
使用float
操作数执行浮点除法。
使用以下任一选项:
time = samplesPerPeriod / 44.0f;
或
此外,您的time
对象是float
类型。使用44.0f(afloat
literal)而不是44.0(adouble
literal),可以保证使用float
而不是double
操作数执行除法。例如,如果您的CPU只能执行FPU单精度,这可能非常关键。使用double
文字将强制软件模拟double
类型的操作数的除法。请注意,gcc在这种情况下有一个警告选项:
-Wdouble promotion
假设samplesperperion
为整数类型
float time;
time = samplesPerPeriod / 44;
然后,/运算符的两个操作数都是整数类型,并执行整数除法
使用float
操作数执行浮点除法。
使用以下任一选项:
time = samplesPerPeriod / 44.0f;
或
此外,您的time
对象是float
类型。使用44.0f(afloat
literal)而不是44.0(adouble
literal),可以保证使用float
而不是double
操作数执行除法。例如,如果您的CPU只能执行FPU单精度,这可能非常关键。使用double
文字将强制软件模拟double
类型的操作数的除法。请注意,gcc在这种情况下有一个警告选项:
-Wdouble promotion
是一个整数值吗?是一个整数值吗?