2010-07-15 60 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);