[英]Illegal use of Floating Point error while compiling
I am getting an error as "illegal use of floating point" while running the program below. 运行以下程序时,出现“非法使用浮点数”错误。
How should I fix it. 我应该如何解决。
#include<stdio.h>
#include<conio.h>
int main() {
float x,op;
printf("enter the value of x");
scanf("%f",&x);
op=(x^1/2+x^2/3+x^3/4)/(x^5/2+x^7/2);
printf("Final Op is %f\n",op);
return 0;
}
In C, ^
is used as the bitwise XOR operator. 在C中,
^
用作按位XOR运算符。 Each of the operands shall have integer type. 每个操作数应具有整数类型。
2 Each of the operands shall have integer type.
2每个操作数应具有整数类型。
4 The result of the^
operator is the bitwise exclusive OR of the operands [...]4
^
运算符的结果是操作数的按位异或[...]
You need the standard library function powf
: 您需要标准的库函数
powf
:
float powf(float x, float y);
Include math.h
header in your program. 在程序中包含
math.h
标头。
Also note that as pointed out by @Jens Gustedt 1/2
, 2/3
and 3/4
will all return 0
because they are integer division. 还要注意,正如@Jens Gustedt指出的那样,
1/2
2/3
和3/4
将全部返回0
因为它们是整数除法。 You need to change them to 1.0/2
, 2.0/3
and 3.0/4
. 您需要将它们更改为
1.0/2
2.0/3
和3.0/4
。
In C and related languages ^
is the bitwise XOR operator. 在C和相关语言中,
^
是按位XOR运算符。 For exponentiation you need pow()
or powf()
. 为了求幂,您需要
pow()
或powf()
。
Change: 更改:
op=(x^1/2+x^2/3+x^3/4)/(x^5/2+x^7/2);
to: 至:
op = (pow(x, 1./2) + pow(x, 2./3) + pow(x, 3./4)) / (pow(x, 5./2) + pow(x, 7./2));
Make sure you #include <math.h>
. 确保您
#include <math.h>
。
Also you might want to get a good introductory book on C and read up on operators and math library functions. 另外,您可能想获得一本有关C的入门书籍,并阅读有关运算符和数学库函数的内容。
#include <stdio.h>
#include <math.h>
int main()
{
float x, op;
printf("Enter the value of x: ");
scanf("%f", &x);
op = (pow(x, 1./2) + pow(x, 2./3) + pow(x, 3./4)) / (pow(x, 5./2) + pow(x, 7./2));
printf("\nFinal op is %f\n", op);
return 0;
}
There are two problems with the op
expression: op
表达式有两个问题:
^
is not the exponential operator in C, it is bitwise-XOR and required integer operands. ^
不是C中的指数运算符,它是按位XOR运算和必需的整数操作数。 /
are integers, then an integer divide is performed, which truncates to the integer nearest zero. /
两个操作数均为整数时,将执行整数除法,该运算将截断为最接近零的整数。 So for example 7/2 == 3
. 7/2 == 3
。 You must make one or both operands floating point to perform floating point division such that 7.0/2.0 == 3.5
7.0/2.0 == 3.5
. 。
#include <math.h>
...
op = ( pow( x, 1.0/2.0 ) +
pow( x, 2.0/3.0 ) +
pow( x, 3.0/4.0) ) /
( pow( x, 5.0/2.0 ) +
pow( x, 7.0/2.0 ) ;
Note that the expression involves an implicit cast to float
. 注意,该表达式涉及一个隐式强制转换为
float
。 In C89 the math functions are defined for double
- so the cast cannot be avoided. 在C89数学函数的定义
double
-所以无法避免的演员。 C99 provides float
variants; C99提供了
float
变体; eg powf()
, and C++ overloads them so that the type is determined by the operands; 例如
powf()
,并且C ++重载它们,以便由操作数确定类型; eg pow(7.0f/2.0f)
. 例如
pow(7.0f/2.0f)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.