-2

How to define such an expression in c language :

x+(x^2)/(2*2-1)

where x is a real number.

I tried to enter the expression as it is but that didn't help.

the thing is I don't want to use any self-defined functions, just loops.

any ideas anyone?

Marievi
  • 4,951
  • 1
  • 16
  • 33
Ali Haroon
  • 83
  • 1
  • 4
  • 12
  • The '/' operator is the correct operator for representing division. When you say "that didn't help" what do you mean? What error did you get? – Scott Thompson Apr 01 '16 at 08:24
  • maybe the operator error is with '^'? – Dr. Stitch Apr 01 '16 at 08:25
  • 2
    In C, the caret `^` is the bitwise xor operator, which can only operate on integer types. There is no power operator, but you can calculate x² as `x*x` or use `pow(x, 2)` from ``. – M Oehm Apr 01 '16 at 08:25

2 Answers2

1

In C, ^ is the bitwise XOR operator. There is no "power of" operator.

So the C equivalent would look like this:

x+(x*x)/(2*2-1)

Operator precedence is just as for math, so note that the above is equivalent to

x + ( (x*x) / ((2*2)-1) )

If you need a variable "raise x to the power of y", there is unfortunately only the pow() function, which works on floating point variables, and is therefore somewhat bloated and inefficient. However, writing your own integer version of it is trivial, see this.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396
0

First of all, in code, you will have to lay ground for displaying the result of what you want. Typing expressions "as is" into c code will do nothing for you. Here is an example of a simple c program that will do what you want:

#include <stdio.h>

int main (void) {
int x, result;
x = 10; // x is 10 for this example, but you may assign any number where both x and result are within the range of integers
result = x + ( x * x ) / ( 2 * 2 - 1 );
printf("The result is : %d", result);
return 0;
}

The key points here are:

  • a ^ 2 in c programming does not represent computing the power, its a bitwise XOR instead.
  • a ^ 2 can be simplified to a * a through basic mathematics.
  • to compute a number in c you need to actually compute it, not just calculate it (the printf statement for instance prints this to the console from which the program is run in my example)
Magisch
  • 7,312
  • 9
  • 36
  • 52