Reputation: 1
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;
}
Upvotes: 0
Views: 3233
Reputation: 213170
In C and related languages ^
is the bitwise XOR operator. For exponentiation you need pow()
or 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>
.
Also you might want to get a good introductory book on C and read up on operators and math library functions.
#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;
}
Upvotes: 0
Reputation: 106102
In C, ^
is used as the bitwise XOR operator. Each of the operands shall have integer type.
2 Each of the operands shall have integer type.
4 The result of the^
operator is the bitwise exclusive OR of the operands [...]
You need the standard library function powf
:
float powf(float x, float y);
Include math.h
header in your program.
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. You need to change them to 1.0/2
, 2.0/3
and 3.0/4
.
Upvotes: 3
Reputation: 93556
There are two problems with the op
expression:
^
is not the exponential operator in C, it is bitwise-XOR and required integer operands./
are integers, then an integer divide is performed, which truncates to the integer nearest zero. So for example 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
.
#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
. In C89 the math functions are defined for double
- so the cast cannot be avoided. C99 provides float
variants; e.g. powf()
, and C++ overloads them so that the type is determined by the operands; e.g. pow(7.0f/2.0f)
.
Upvotes: 0