Improper syntax in math operator? maybe?

 Jeremy Bayman · March 17, 2015 Just started to learn C (and programming in general) about a month ago, today i figured it would be good practice to try to create a program to solve an equation for my math class rather than my calculator. I am trying to evaluate the function f(x)=x^3-8x^2-31x-22. So far i wrote#include #include int main(){int xVal, remThereom;scanf(" %d", &xVal);remThereom = ((xVal^3) - (8*(xVal^2))-(31*xVal)-22); // xVal = -2 how does yVal evaluate to -69?printf(" %d", remThereom);return 0;}the code runs but produces the wrong result (i wrote the input and output in the comment), can't figure out why, if anyone can explain I'm sure it is something basic missing. So far took a 30 min hmwk assignment and made it 2 hours trying to figure this out myself please help if you can.

Replies

 Cody Treadway · March 17, 2015 The ^ operator is not used for powers. It is actually the bitwise XOR. Use the pow function from math.h#include remThereom = pow(xVal,3) - (8 * pow(xVal,2)) - (31 * xVal) - 22;You should also not assume that scanf found an integer. You should test the return value. xVal will be uninitialized if scanf returns 0 or EOF and you will be lucky to get a seg fault during your calculation. Dol Lod · March 17, 2015 ^ is not an exponent. Please look up C math. ^ is a bitwise logical operator that does a totally different operation.
• 1

C

118,398 followers