开发者

code from hackers delight

/* 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;
}

i have tested it in c++

#include <iostream>
using namespace std;

char *binary(unsigned k){

    int i, j;
    static cha开发者_如何转开发r 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;
}

but what value does k have ? for example i have entered 127 but it return 0 why?


You're throwing away the return value of the function binary :

*binary(k);

binary returns a char * which is (as the documentation says) "intended for use with printf", but you aren't doing anything with this string. Your program 'returns' 0 because that's what you're explicitly returning with your last line of code!

Try changing

*binary(k);

to

cout << binary(k);

and you should at least see some output.


Change:

  cin>>k;
  *binary(k);

to:

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


Perhaps you should print out the binary string?

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


Try this C++ code instead:

#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;
}

Notice that this line has changed:

cout << *binary(k);


As it should. I'm not all that familiar with C++, but the basics are still the same. The *binary function returns the value back to the previous function, it doesn't return that value for the entire page.

For example:

k = myFunction();
return 0;

Your myFunction gets executed and that returned value gets set into the variable k, then it continues the rest of the function and returns 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜