2015-11-01 70 views
0
#include <stdio.h> 
#include <math.h> 

long factcalc(int num1); 

int main(void) 
{ 
    int num1; 
    long factorial; 
    int d; 
    int out; 

    printf("Please enter a number that is greater than 0"); 
    scanf_s("%d", &num1); 

    if (num1 < 0) { 
     printf("Error, number has to be greater than 0"); 
    } else if (num1 == 0) { 
     printf("\nThe answer is 1"); 
    } else { 
     factorial = factcalc(num1); 
     printf("\nThe factorial of your number is\t %ld", factorial); 
    } 

    return 0; 
} 

long factcalc(int num1) 
{ 
    int factorial = 1; 
    int c; 

    for (c = 1; c <= num1; c++) 
    factorial = factorial * c; 

    return factorial; 
} 

我在想,如何讓程序不斷詢問用戶輸入,直到用戶輸入'-1'?因此,即使在計算了一個數字的階乘之後,它仍會要求更多的數字,直到用戶輸入-1,同樣,當它顯示錯誤消息等時也是如此。提前致謝。如何在沒有轉到語句的情況下返回到我的程序的開始

+1

爲什麼不使用循環?我認爲不需要'goto'。 – ameyCU

回答

5

通過引入無限循環可以輕鬆實現。

#include <stdio.h> 
#include <math.h> 

#ifndef _MSC_VER 
#define scanf_s scanf 
#endif 

long factcalc(int num1); 

int main(void) 
{ 
    int num1; 
    long factorial; 
    int d; 
    int out; 

    for (;;) { 
     printf("Please enter a number that is greater than 0"); 
     scanf_s("%d", &num1); 
     if (num1 == -1) { 

      break; 
     } 

     else if (num1 < 0) { 

      printf("Error, number has to be greater than 0"); 
     } 

     else if (num1 == 0) { 

      printf("\nThe answer is 1"); 
     } 

     else { 

      factorial = factcalc(num1); 
      printf("\nThe factorial of your number is\t %ld", factorial); 
     } 
    } 

    return 0; 
} 

long factcalc(int num1) { 

    int factorial = 1; 
    int c; 

    for (c = 1; c <= num1; c++) 
     factorial = factorial * c; 

    return factorial; 
} 
1

有選擇的幾個場景中使用goto是「還行」,但這個肯定不是一個。

首先,將程序的相關位放入函數中。

然後,監視器和使用用戶輸入像這樣:

int number = -1; 

while (scanf("%d", &number)) { 
    if (-1 == number) { 
     break; 
    } 

    call_foo_function(number); 
} 
0

是,通過@ameyCU所建議的,使用環是溶液。例如,

while (1) 
{ 
    printf("Please enter a number that is greater than 0"); 
    scanf_s("%d", &num1); 

    if (-1 == num1) 
    { 
     break; 
    } 

    // Find factorial of input number 
    ... 
    ... 

    // Loop back to get next input from user 
} 
相關問題