-1

This isn't returning any answer at all when I run it. I can't quite figure out why. Basically I need to multiply each digit of a given number by its base raised to the degree equal to the number of digits. the power decrements each time it runs. Or it should, anyway. It doesnt.

int num, sum, base;
sum = 0;
cout << "num";
cin >> num;
cout << "base";
cin >> base;

int power = 0;

while (num > 0)
{
    power++;
    num = num/10;
}
return power;
sum = 0 ;
while (num > 0);
{
    sum = (num%10)*(pow(base, power));
    num = num/10;
    power--;


}
sum += sum;

cout << sum;
bc8787
  • 41
  • 1
  • 6
  • 6
    You are returning `power`. If this is your main method you are exiting at that point. Either way everything after it is [dead code](http://en.wikipedia.org/wiki/Dead_code). – Paul Jun 27 '13 at 21:17
  • Ah, okay. I fixed that. Now it prints out an answer, it's just the wrong one. Progress. Thanks. Any ideas as to why it's giving me the wrong answer? – bc8787 Jun 27 '13 at 21:20
  • @BryanCoxwell what answer is it giving? – Sam I am says Reinstate Monica Jun 27 '13 at 21:21
  • Now it should print `0` because num is already `0` when the second loop starts, so that loop is never entered. You should copy `num` in advance and use the copy for one of your loops. – Paul Jun 27 '13 at 21:21
  • 2
    Please compile with warnings enabled. it would have told you about 'unreachable code'... – Michael Dorgan Jun 27 '13 at 21:23
  • possible duplicate of [Create char array of integer using digits as size](http://stackoverflow.com/questions/16974382/create-char-array-of-integer-using-digits-as-size) – Mooing Duck Jun 27 '13 at 21:51
  • wait what? I didn't want to close as a dupe of _that_! I misclicked :( – Mooing Duck Jun 27 '13 at 21:51
  • `num` is never restored to its original value. If you fix that, then the second loop will spin indefinitely because of that `;`. – sh1 Jun 27 '13 at 22:49
  • Post the entire code. I can't tell if this is a separate function or part of `main`. – Thomas Matthews Jun 28 '13 at 00:30
  • 1
    Looks like you don't understand the algorithm. Using pen and paper, write the steps (in your language, not C++) to perform the requirements. Run through them and modify as necessary. When you have the algorithm working, translate the algorithm to C++. – Thomas Matthews Jun 28 '13 at 00:32

1 Answers1

3

Looking at your code, it looks like you have a rogue return statement in the middle of your function. At least I'm assuming its a function as you don't have a proper function definition in your code.

Remove it and try again!

return power; <-- right here your function will return and no code underneath will be executed
sum = 0 ;
while (num > 0);
{
    sum = (num%10)*(pow(base, power));
    num = num/10;
    power--;
}
sum += sum;

cout << sum;
chollida
  • 7,834
  • 11
  • 55
  • 85
  • Dunno -- to me the return looks the same color blue as the rest of the code. But then, I'm color-blind. – Hot Licks Jun 27 '13 at 21:51