簡體   English   中英

“%d! =%ld'n”是指此代碼?

[英]What does “%d! = %ld'n” mean in this code?

我仍然是C語言的初學者,所以我很難理解“%d!=%ld”。 我知道%d和%ld分別用於整數和long,所以“!=”使我感到困惑。

#include<stdio.h>
long factorial(int);
int main() {
  int n;
  long f;
  printf("Enter an non-negative integer: ");
  scanf("%d", &n);
  if (n < 0)
    printf("Negative integers are not allowed.\n");
  else {
    f = factorial(n);
    printf("%d! = %ld\n", n, f); //what does this mean?
  }
  return 0; }
long factorial(int n) {
  if (n == 0)
    return 1;
  else
    return(n * factorial(n-1)); }

這將打印:

  • %d ,即int n的十進制值
  • ! = ! = ,即文字字符序列
  • %ld ,即long f的十進制值

%d%ldprintf intlong int的格式占位符。 如注釋中所述,感嘆號只是階乘符號。

printf()允許您打印一個帶有變量的字符串。 假設您有一個變量i ,其中包含一個整數7。

printf("My variable is %d", i);

將打印

My variable is 7

到控制台! 這是因為%d是您告訴printf()的方式,“嘿,在這里放一個整數變量!”。 然后將整數作為函數的下一個參數提供。 在您的情況下,%d表示整數n ,而%ld表示整數f 由於f可能確實很大,因此我們將其設置得較長,這意味着您的計算機內部會為其分配更多的字節。 因此,例如,如果我們想獲取因子5並打印出來,我們可以執行以下操作:

printf("Factorial of %d equals %ld\n", 5, factorial(5))
// this will print "Factorial of 5 is 120" then a newline

哦, \\n僅表示打印換行符后綴!

printf("%d! = %ld\n", n, f); //what does this mean?

%d將整數打印為帶符號的十進制數字。

l指定參數是適當的long intunsigned long int 然后, %ld打印long intunsigned long int

打印的文字將變成類似

n! = f 

(階乘符號n!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM