| ||||||||||||||||||||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Functions and powers
I have written a program to have the user enter 2 values and put the first one as the base and the second as the exponent. It comes out the right answer but it still says error. I'm not sure why when the answer is right it outputs error instead of verified. I also want to know why it only verifies certain numbers
#include <iostream> #include <math.h> #include <stdlib.h> using namespace std; float add (float a, float b) { float c = a + b; return c; } float subtract (float a, float b) { float c = a - b; return c; } float multiply (float a, float b) { float c = a * b; return c; } float divide (float a, float b) { float c = (a/b); return c; } float pow ( int a, int b) { float c = a^b; return c; } int main () { float x; float y; cout << "Please enter a number " << endl; cin >> x; cout << " Please enter an integer " << endl; cin >> y; float power = pow (x,y); cout << "The answer is " << power << endl; if (power == pow (x,y)) { cout << "Verified" << endl; } else if ( power != pow (x,y)) { cout << "Error" << endl; } return 0; } |
|
#2
|
|||
|
|||
|
Are you using a C compiler or C++ compiler? The header file used by C++ for the function pow() is cmath: Header File: math.h (C) or cmath (C++). Hope this helps.
|
|
#3
|
|||
|
|||
|
Thank you!!
|
|
#4
|
||||
|
||||
|
Quote:
You -may- have heard of why == is usually a bad idea on floats: http://www.parashift.com/c++-faq-li....html#faq-29.17 Make sure to also read the one just below it; it's even more relevant for your situation. Have you considered the possibility of both your ifs (verified/error) being false yet? Code:
float pow ( int a, int b)
{
float c = a^b; // oops... ^ is the xor operator, not the power operator
return c;
}
That is returns the correct answer means it's not calling your function. (See overload resolution; you have several pow() taking two arguments in scope, and it picks the best one based on the arguments you pass to it) The correct thing to do in any case is to call the standard library function pow(), instead of defining your own, (usually, like here) incorrect one. Having included <math.h> it's already there for your use. <cmath> usually contains something along the lines of namespace std { #include <math.h> } so with the using namespace std; in place there's no real difference.
__________________
Quote:
Last edited by MaHuJa : November 6th, 2009 at 07:11 PM. |
|
#5
|
|||
|
|||
|
Oh great thank you! I am VERY new to this so I'm just picking up things as I go.
|
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Functions and powers |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|