rfact.cpp

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

CPP
28
字号
#include <iostream.h>
#include <stdlib.h>
#include <assert.h>

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

long rfact(int n) { // n! must fit in a long variable, so n <= 12
  assert((n >= 0) && (n <= 12)); // Base case: legal bounds
  if (n <= 1)  return 1;         // Base case: return base solution
  return n * rfact(n-1);         // Recursive call for n > 1
}

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

  if(argc < 2)
    cout << "Usage: rfact <n>\n";
  else {
    n = atoi(argv[1]);
    if (n > 12) // 12! is the biggest value that will fit into a long int
      cout << "Sorry, your value for n is too big\n";
    else
      cout << "The factorial of " << n << " is " << rfact(n) << "\n";
  }
  return 0;
}

⌨️ 快捷键说明

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