2010-07-15 61 views
1
/* Converts the unsigned integer k to binary character form with a blank 
after every fourth digit. Result is in string s of length 39. Caution: 
If you want to save the string, you must move it. This is intended for 
use with printf, and you can have only one reference to this in each 
printf statement. */ 
char * binary(unsigned k) { 
    int i, j; 
    static char s[40] = "0000 0000 0000 0000 0000 0000 0000 0000"; 

    j = 38; 
    for (i = 31; i >= 0; i--) { 
     if (k & 1) s[j] = '1'; 
     else  s[j] = '0'; 
     j = j - 1; 
     k = k >> 1; 
     if ((i & 3) == 0) j = j - 1; 
    } 
    return s; 
} 

我在C++代碼黑客喜悅

#include <iostream> 
using namespace std; 

char *binary(unsigned k){ 

    int i, j; 
    static char s[40]="0000 0000 0000 0000 0000 0000 0000 0000"; 
    j=38; 
    for (i=31;i>=0;i--){ 
     if (k & 1) s[j]='1'; 
     else s[j]='0'; 
     j=j-1; 
     k=k>>1; 
     if ((i & 3)==0) j=j-1; 
    } 
    return s; 
} 

int main(){ 

    unsigned k; 
    cin>>k; 
    *binary(k); 

    return 0; 
} 

測試,但不ķ什麼價值呢?例如我已經輸入127,但它返回0爲什麼?

回答

7

你把自己的功能binary的返回值:

*binary(k); 

binary返回char *這是(如文檔說)「旨在與printf的使用」,但你不是做任何與此字符串。你的程序'返回'0,因爲這就是你最後一行代碼顯式返回的內容!

嘗試改變

*binary(k); 

cout << binary(k); 

,你至少應該看到一些輸出

0

因爲它應該。我並不是那麼熟悉C++,但基礎知識仍然是一樣的。 *binary函數將該值返回到前一個函數,它不會爲整個頁面返回該值。

例如:

k = myFunction(); 
return 0; 

myFunction被執行和返回值被設置成變量k,那麼它延續了函數的其餘部分,並返回0

1

變化:

cin>>k; 
    *binary(k); 

到:

cin >> k; 
    cout << binary(k) << endl; 
1

也許你應該打印出二進制字符串?

unsigned k; 
cin >> k; 
cout << binary(k) << endl; 
1

嘗試此C++代碼,而不是:

#include <iostream> 
using namespace std; 
char *binary(unsigned k){ 
    int i, j; 
    static char s[40]="0000 0000 0000 0000 0000 0000 0000 0000"; 
    j=38; 
    for (i=31;i>=0;i--) { 
    if (k & 1) s[j]='1'; 
    else s[j]='0'; 
    j=j-1; 
    k=k>>1; 
    if ((i & 3)==0) 
     j=j-1; 
    } 
    return s; 
} 

int main(){ 
    unsigned k; 
    cin>>k; 
    cout << k << " : " << binary(k) << endl; 

    return 0; 
} 

注意,此線路已改變:

cout << *binary(k);