2016-04-05 57 views
2

我創建一個顯示數的方法,使用逆程序的:逆一個數,C++


123 ==> 3*10^2 + 2*10^1 + 1*10^1 = 321 

但輸出始終爲0任何幫助?

#include <stdio.h> 

int power(int a) 
{ 
    int i; 
    int x = 1; 
    for (i = 1; i = a; i++) 
    { 
     x = x * 10; 
    } 
    return x; 
} 

int inv(int b) 
{ 
    int z = b, j = 0, s = 0, y; 

    for (z = b; z = 0; z = z/10) 
    { 
     for (y = z; y = 0; y = y/10) 
     { 
      j++; 
     } 
     s = s + (z % 10)*power(j - 1); 
    } 
    return s; 
} 


int main() 
{ 
    printf("please enter a number"); int n; 
    scanf("%d", &n); 
    printf("%d", inv(n)); 
    return 0; 
} 
+6

嘗試在調試器中單步調試程序。它應該馬上揭示一些問題。 –

+1

由於我們不是調試器(大概你們都不是),所以你可能想要考慮爲你的變量命名更具描述性。表達式s = s +(z%10)* power(j-1)'對我來說是沒有意義的,除非我經歷整個函數來試圖找出什麼是''''''z'和'j' 。對於(z = b; z = 0; z = z/10)'看起來不正確的' – CompuChip

+0

'。也許'z!= 0'。 –

回答

1

你認爲這兩個for-loop會繼續嗎?
你覺得他們什麼時候會停下來?
(提示:你錯了)

關注z和y的調試器的值。

for (z = b; z = 0; z = z/10) 

for (y = z; y = 0; y = y/10) 
1

您的for循環設置不正確。

for (z = b; z = 0; z = z/10) 

它應該是:

for (z = b; z == 0; z = z/10) 

「Z = 0」 是一個賦值,其始終返回false。所以,你從來沒有進入你的for循環,返回「S」,這是0

+1

計算位數,是的,我的壞分配是法語的,在編程時混合使用,壞習慣 – Karlyr

+0

分配也是英語,但意味着[其他](http://www.dictionary.com/browse/assignation?s=t);) –

+1

'z = 0'將評估爲false –

1

這裏的初始值是反函數的定義,無需任何power function.Keep的代碼短&簡單

int inverse(int b) 
{ 
    int s=0; 
    while(b > 0) 
    { 
     s = s*10 + (b % 10); 
     b /= 10; 
    } 
    return s; 
} 

爲了您上面的查詢,這裏是一個for循環在C語法:

for (init; condition; increment) { 
    statement(s); 
} 
+0

我改正了所有的條件和相同的結果......我的想法是設置一個計數器j,然後使用「最後一位數* 10 ^(j-1)... – pioneer

1

爲什麼不使用string和扭轉這種局面?這當然只適用於如果你可以自由選擇你的方法。

#include <iostream> 
#include <string> 
#include <algorithm> 

int reverse(const int n) 
{ 
    std::string s = std::to_string(n); 
    std::reverse(s.begin(), s.end()); 
    return std::stoi(s); 
} 

int main() 
{ 
    int number; 
    std::cin >> number; 
    std::cout << reverse(number) << std::endl; 
    return 0; 
}