2017-01-18 4 views
0

Для моего задания моя программа должна спросить у пользователя, какая из пяти функций он хочет выполнить. Эти функции включают в себя пяти:, используя несколько различных функций.

  1. суммирования ряда
  2. факториала числа
  3. Фибоначчи значения го члена.
  4. gcd двух чисел
  5. a к власти b.

Пользователю будет предложено несколько раз, пока он не захочет выйти. Все мои функции работают нормально. Тем не менее, я думаю, что я перепутал одну из циклов, потому что, как только я вхожу в какую-то функцию, которую я хочу выполнить, и введите значение, он продолжает отображать ответ в бесконечном цикле.

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

// function to find summation of a number 
int summation(int k) { 
    int i; 

    for(i = k; i >= 0; i--) { 
    k = i + (i-1); 
    } 
    return k; 
} 

// function to find the factorail of a number 
int factorial(int num) { 
    int i; 

    for(i = num - 1; i > 0; i--) { 
    num = num * i; 
    } 
    return num; 
} 

// dunxtion to find the fibonacci of the nth term 
int fibonacci(int n){ 
    int i, t1 = 0, t2 = 1, nextTerm; 

    for(i = 1; i <= n; i++) { 
    if(i == 1) { 
     printf("%d, ", t1); 
     continue; 
    } 
    if(i == 2) { 
     printf("%d, ", t2); 
     continue; 
    } 
    nextTerm = t1 + t2; 
    t1 = t2; 
    t2 = nextTerm; 
    printf("%d, ", nextTerm); 
    } 
    return nextTerm; 
} 

// function to find the gcd of two numbers 
int gcd(int n, int m) { 
    int i, gcd; 

    for(i=1; i <= n && i <= m; i++) { 
    // Checks if i is a factor of both integers 
    if(n % i == 0 && m % i == 0) 
     gcd = i; 
    } 
    return gcd; 
} 

// function to find value of n to the power of m 
int power(int n, int m) { 
    return pow(n, m); 
} 

int main(void) {; 
    int option ,n, m; 

//Asks user for what they want to find 
    printf("If you would like to find the summation of a number, enter 1 \n"); 
    printf("If you would like to find the factorial of a number, enter 2 \n"); 
    printf("If you would like to find the fibonacci sequence of a number, enter 3 \n"); 
    printf("If you would like to find the gcd of two numbers, enter 4 \n"); 
    printf("If you would like to find the power of a number a to b, enter 5 \n"); 
    printf("If you would like to exit, enter 0 \n"); 
    scanf("%d", &option); 

// Enables the program to prompt the user until they wish to exit 
    while(option != 0) { 
    switch(option) { //If user wishes to find the summation 
     case 1: if(option == 1) { 
        printf("Enter a number: "); 
        scanf("%d", &n); 
        while(n > 0) { 
         if(n < 1) { //message displayed if an invalid value is entered 
          printf("invalid value"); 
         } 
         else { 
          printf("Summation of %d is %d", n, summation(n)); 
         } 
        } 
       } 
     case 2: if(option == 2) { //if user wishes to find factorial of a number 
        printf("Enter a number: "); 
        scanf("%d", &n); 
        while(n >= 0) {//message displayed if an invalid value is entered 
         if(n < 0) { 
          printf("invalid value"); 
         } 
         else { 
          printf("factorial of %d is %d", n, factorial(n)); 
         } 
        } 
       } 
     case 3: if(option == 3) { //if user wishes to find the fibonacci value of the nth term 
        printf("Enter a number: "); 
        scanf("%d", &n); 
        while(n >= 0) {//message displayed if an invalid value is entered 
         if(n < 0) { 
          printf("invalid value"); 
         } 
         else { 
          printf("fibonacci of %d is %d", n, fibonacci(n)); 
         } 
        } 
       } 
     case 4: if(option == 4) { 
        printf("Enter a number: "); 
        scanf("%d %d", &n, &m); 
        while(n >= 0 && m >= 0) { 
         if(n < 0 || m < 0) {//message displayed if an invalid value is entered 
          printf("invalid value"); 
         } 
         else { 
          printf("GCD of %d and %d is %d", n, m, gcd(n, m)); 
         } 
        } 
       } 
     case 5: if(option == 5) { 
        printf("Enter a number: "); 
        scanf("%d %d", &n, &m); 
        while(n >= 0 && m >= 0) { 
         if(n <= 0 || m < 0) { 
          printf("invalid value"); 
         } 
         else { 
          printf("%d to the power of %d is %d", n, m, power(n, m)); 
         } 
        } 
       } 
     default: if(option == 0) { 
      break; 
     } 
    } 
    scanf("%d", &option); 
} 
} 
+0

Вы хотите создать [___MCVE___] (http://stackoverflow.com/help/mcve)? –

+1

'if (option == 1)' и так же .. D.R.Y. –

+1

Проверьте возвращаемое значение из 'scanf()'. –

ответ

0

Прежде всего, C имеет неструктурированный switch заявление.

Вы должны добавить break; заявления после того, как каждый из ваших case тела предела Казни для конкретного случая к телу, упомянутому в этой case.

В противном случае, по умолчанию, (при отсутствии break заявления) все case заявления работает в осенне-через образом. Вы можете узнать больше об этом here.


Тем не менее, в отношении повторного выполнения одной функции, есть серьезный недостаток в большинстве (если не все) из логики. Например, давайте рассмотрим этот

while(n > 0) { 
    if(n < 1) { //message displayed if an invalid value is entered 
     printf("invalid value"); 
    } 
    else { 
     printf("Summation of %d is %d", n, summation(n)); 
    } 
    } 

здесь, вы отвечаете на n становится 0 в какой-то момент, чтобы вырваться из петли, но вы не изменяли n, вообще.

Разрабатывать, C использует передачу по значению для передачи аргументов, так что для вызова, summation(n), внутри функции, независимо от изменения, вносимые в параметр, получающего значение n, не отражается в вызывающем и таким образом, n в вызывающем абоненте остается неизменным.

+0

Да, я совсем забыл о заявлениях о перерывах. Но даже после их добавления у него все еще есть та же проблема. –

+0

@ShoaibAhmed вы имеете в виду, что он все еще выполняет _all_ функции? –

+0

Все функции не выполняются. Скажем, я ввожу 2 для переменной «option», которая находит факториал введенного числа. Функция выполнена правильно. Единственная проблема заключается в том, что он постоянно отображает ответ в бесконечном цикле. –

0

Вам просто нужно break заявления в конце каждого случая как:

case 1: if(option == 1) { 
       printf("Enter a number: "); 
       scanf("%d", &n); 
       while(n > 0) { 
        if(n < 1) { //message displayed if an invalid value is entered 
         printf("invalid value"); 
        } 
        else { 
         printf("Summation of %d is %d", n, summation(n)); 
        } 
       } 
      } 
break; 

Поскольку контроль упадет до следующего случая, если никакого заявления перерыва нет.

Смежные вопросы