collatz.cpp

来自「经典c++程序的实现」· C++ 代码 · 共 36 行

CPP
36
字号
#include <iostream.h>
#include <stdlib.h>

#include "..\include\book.h"

int main(int argc, char** argv) {
  int n;

  if(argc != 2) {
    cout << "Usage: collatz <start value>\n";
    exit(-1);
  }

  n = atoi(argv[1]);

cout << "The start value for the Collatz sequence is: " << n << "\n";

#define ODD(X) ((X) & 1)

// Include the version with the print statement.
// The book version has no print statement.
#define ODD(X) ((X) & 1)

while (n > 1) {
  if (ODD(n))
    n = 3 * n + 1;
  else
    n = n / 2;
  cout << n << "  ";
}

cout << "\n";

 return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?