| | |
Function randomly loops
Please support our C++ advertiser: Intel Parallel Studio Home
![]() |
•
•
Join Date: Jan 2009
Posts: 1
Reputation:
Solved Threads: 0
Hey - I'm new asking questions here. I'm writing a simple program to give a number to a power using a recursive function (inconvenient, but that's the assignment). It seems as though the program should work, and debugging shows that it almost does. It has the right value up until it's about to return, and then it jumps back and multiplies the value further. For the purposes of debugging, it has been modified to only take 5^3.
Take a look:
I'm totally confused as to why this would happen. Any ideas?
Take a look:
C++ Syntax (Toggle Plain Text)
// Recursive Power Program #include <iostream> using namespace std; int power(int, int, int); int main() { int num = 5, pow = 3, full; //cin >> num; - out for the purposes of debugging; the program will return 5^3 //cin >> pow; full = num; cout << power(num, pow, full); char response; cin >> response; } int power(int num, int pow, int full) { if (pow > 1) { full = num * full; //Multiplies the original number by itself, and sets the new amount to full return (num * power(num, --pow, full)); //Multiplies the original number by full again and again until pow is 1 } else { cout << full; //Just to make sure full had the correct value here (it did) return full; //The problem is here. Full = 125 here, but it then jumps back up to the return in the IF statement above, multiplying it 3 more times... } }
I'm totally confused as to why this would happen. Any ideas?
The if statement is wrong. It should be:
Also, your code breaks when pow = 0. Anyway, it's an easy thing to fix.
cpp Syntax (Toggle Plain Text)
if (pow > 1) { full = num * full; return (power(num, --pow, full)); //You've already multiplied once. Don't do it again. }
Also, your code breaks when pow = 0. Anyway, it's an easy thing to fix.
Last edited by devnar; Jan 18th, 2009 at 2:47 am.
![]() |
Similar Threads
- Simple Guessing Program (C)
- looping problem (C++)
Other Threads in the C++ Forum
- Previous Thread: any suggestion?
- Next Thread: C++ permutations of 6 numbers. help!
| Thread Tools | Search this Thread |
api array based binary c++ c/c++ calculator char char* class classes code coding compile console conversion count database delete deploy desktop developer directshow dll download dynamic dynamiccharacterarray email encryption error file forms fstream function functions game givemetehcodez google graph gui homeworkhelp iamthwee ifstream input int integer java lib linkedlist linker linux list loop looping loops map math matrix memory multiple news number numbertoword output parameter pointer problem program programming project python random read recursion recursive reference return rpg sorting string strings struct temperature template templates test text text-file tree unix url variable vector video visualstudio win32 windows winsock wordfrequency wxwidgets





