簡體   English   中英

我在 C 中做了一個簡單的程序來計算一個數字的階乘

[英]I made a simple program in C which calculates the factorial of a number

我用 C 編寫了一個簡單的程序來計算一個數字的階乘,但最后我想(再次)運行該程序。 而不是看到“按任意鍵繼續”,我希望它顯示“按任意鍵再次查找數字的階乘”。

代碼:

#include<stdio.h>
int main()
{
    int facto, i, m ;
    m=1 ;
    printf("Ener a Value : ");
    scanf("%d", &facto) ;
    for( i=facto-1 ; i>m ; i-- )  
        facto *= i ; 
    printf("My Reg num:SP-16/BBS/033\nFactorial of the number : =%d\n", facto );
    system ("pause") ;
} 

“按任意鍵繼續”

此行來自您的system(pause) 如果你想:

1.. 找到另一個階乘

2.. 打印另一個消息

你應該像這樣使用一個循環和一個 printf

#include<stdio.h>
int main()
{
  int facto, i, m ;
  m=1 ;
  printf("Ener a Value : ");
  while( 0 < scanf("%d", &facto) && facto > 0){
    for( i=facto-1 ; i>m ; i-- )  
      facto *= i ; 
    printf("My Reg num:SP-16/BBS/033\nFactorial of the number : =%d\n",facto); 
  printf("press any key to find factorial of a number again : ");
  }
  return 0;
} 

首先,我要指出,你的問題還很不清楚。 如果您的意思是希望只要用戶願意就可以連續運行程序,那么我建議將階乘查找代碼放在 do-while 循環中。 while 條件將基於“選擇”變量。 只有當'choice' 變量接收到'n' 的輸入時(因為程序必須在某個時刻結束),代碼才會停止重新運行。

#include <stdio.h>

int main(void) {
int facto, i, m ;
char choice='y';

do{
  printf("Ener a Value : ");
  scanf("%d", &facto);
  m=1 ;
  for( i=facto-1 ; i>m ; i-- )  
    facto *= i ; 

  printf("My Reg num:SP-16/BBS/033\nFactorial of the number : =%d\n",facto );
  printf("Press any key to find factorial of a number again");
  scanf("%c", &choice);
  } while(choice!='n');

}

您的代碼非常簡單明了 我沒有做任何事情來調整它。

但是,如果您想一次又一次地重新運行整個程序直到某個時刻,您應該始終考慮使用具有特定結束條件循環

試試這個(按回車結束程序,其他任何事情都會重復)

#include<stdio.h>
int main()
{
    int facto, i, m ;
    m=1 ;
    do {
        fflush(stdin);
        system("cls");
        printf("Ener a Value : ");
        scanf("%d", &facto) ;
        getchar();
        for( i=facto-1 ; i>m ; i-- )  
        facto *= i ; 
        printf("My Reg num:SP-16/BBS/033\nFactorial of the number : =%d\n", facto );
        printf("press any key to find factorial of a number again (Enter to end): ");
    }
    while ( getchar()!='\n');
} 

暫無
暫無

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

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