c++ - 黑客喜欢的代码

标签 c++

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

但是 k 有什么值(value)呢?例如我输入了 127 但它返回 0 为什么?

最佳答案

您正在丢弃函数 binary 的返回值:

*binary(k);

binary 返回一个 char * ,它(如文档所述)“旨在与 printf 一起使用”,但您没有对该字符串执行任何操作。您的程序“返回”0,因为这是您在最后一行代码中明确返回的内容!

尝试改变

*binary(k);

cout << binary(k);

你至少应该看到一些输出。

关于c++ - 黑客喜欢的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3253349/

相关文章:

c++ - 错误 : macro names must be identifiers using #ifdef 0

c++ - 始终分配 vs 检查相等性并分配

c++ - C++ 中的 char* vs std::string

c++ - 为什么析构函数调用三次?

c++ - 解交错 PCM (*.wav) 立体声音频数据

c++ - 数组指针算术 - 合法和未定义的行为

c++ - 没有 typedef 的可变参数扩展器

C++:什么是::for?

c++ - 我如何使用 vim cindent 实现这一点?

c++ - 使用 curses 库时使用 move() 或 wmove() 时光标不会移动