2016-12-16 2 views
4

Я новичок в кодировании C.Как я могу отладить эту базовую программу IF-ELSE?

Я написал базовую программу для расчета процента (метод расчета простых процентов является неправильным, но это не то место, где лежит текущая проблема). Я вставляю код здесь, чтобы вы могли лучше понять проблему.

#include <stdio.h> 
#include <stdlib.h> 

int main() 
{ 
    printf("This is a program which calculates your balance each year for 5 years! \n"); 

    char name [30]; 
    float principal; 
    float interestRate; 
    int interestType; 
    int age; 

    printf("Start by entering your name \n"); 
    scanf("%s", name); 

    printf("Please enter the type of interest you earn (Simple = 1, Compound = 2) \n"); 
    scanf("%d", interestType); 

    if (interestType == 1) 
    { 
     printf("You have chosen your interest type as simple \n"); 

     printf("Please enter your age \n"); 
     scanf(" %d", &age); 

     // IF statement 
     if (age < 18) 
     { 
      printf("You're not eligible for a bank account yet"); 
     } 
     // ELSEIF statement 
     else if (age > 122) 
     { 
      printf("Please submit your age to the Guinness Book of World Records and try again"); 
     } 
     //ELSE statement 
     else 
     { 
      printf("Please enter your current account balance \n"); 
      scanf(" %f", &principal); 

      //Nested IF statement 
      if (principal == 0) 
      { 
       printf("You don't have any balance, please fill money in your account and try again \n"); 
      } 
      else 
      { 
       printf("Please enter the rate of interest at which your money is being multiplied \n"); 
       scanf(" %f", &interestRate); 

       // principal *= interestRate is the same as principal = principal * interestRate 
       principal = principal + interestRate; 
       printf("%s's balance after 1 year will be %f \n", name, principal); 

       principal = principal + interestRate; 
       printf("%s's balance after 2 years will be %f \n", name, principal); 

       principal = principal + interestRate; 
       printf("%s's balance after 3 years will be %f \n", name, principal); 

       principal = principal + interestRate; 
       printf("%s's balance after 4 years will be %f \n", name, principal); 

       principal = principal + interestRate; 
       printf("%s's balance after 5 years will be %f \n", name, principal); 

       printf("Thats all"); 
      } 
     } 
    } 

    else if (interestType == 2) 
    { 
     printf("You have chosen your interest type as compound \n"); 

     printf("Please enter your age \n"); 
     scanf(" %d", &age); 

     // IF statement 
     if (age < 18) 
     { 
      printf("You're not eligible for a bank account yet"); 
     } 
     // ELSEIF statement 
     else if (age > 122) 
     { 
      printf("Please submit your age to the Guinness Book of World Records and try again"); 
     } 
     //ELSE statement 
     else 
     { 
      printf("Please enter your current account balance \n"); 
      scanf(" %f", &principal); 

      //Nested IF statement 
      if (principal == 0) 
      { 
       printf("You don't have any balance, please fill money in your account and try again \n"); 
      } 
      else 
      { 
       printf("Please enter the rate of interest at which your money is being multiplied \n"); 
       scanf(" %f", &interestRate); 

       // principal *= interestRate is the same as principal = principal * interestRate 
       principal *= interestRate; 
       printf("%s's balance after 1 year will be %f \n", name, principal); 

       principal *= interestRate; 
       printf("%s's balance after 2 years will be %f \n", name, principal); 

       principal *= interestRate; 
       printf("%s's balance after 3 years will be %f \n", name, principal); 

       principal *= interestRate; 
       printf("%s's balance after 4 years will be %f \n", name, principal); 

       principal *= interestRate; 
       printf("%s's balance after 5 years will be %f \n", name, principal); 

       printf("Thats all"); 
      } 
     } 
    } 

    return 0; 
} 

Проблема я столкнулся в том, что всякий раз, когда программа запускается и запрашивает тип интереса, после того, номер входа (1 или 0) она просто останавливается.

+4

' % 29s ", имя);' –

+1

Привет @SouravGhosh спасибо. Могу ли я узнать, почему вы предлагаете добавить 29 перед s (% 29)? Мне просто интересно :) –

+3

@Rainbowteddycoderguy Число (ширина поля) предотвращает переполнение буфера. Если вы введете больше символов, чем «имя», вы можете получить неопределенное поведение без него. – unwind

ответ

4

Я думаю, вы забыли «&» в scanf("%d", interestType);. Вы должны написать его как scanf("%d", &interestType);. Также вы проверяете входные значения 1 и 2. Вы должны поместить предложение else для обработки недопустимых входов. Оставшийся код работает нормально.

+1

Это была проблема. Благодаря!! Упрощенный и принятый :) –

-6

Вы писали scanf("%s", name); но вы забыли &: scanf("%s", &name);

С строк есть и другие команды, как gets();, что вы, возможно, еще не изучены. Вы должны их проверить, они очень полезны.

+4

Никогда не используйте 'gets'. –

+1

Строки НЕ получают '&'. (это обычная проблема, которая выталкивает всех новичков) – abelenky

+0

Нет, неверный ответ, плохие предложения, пожалуйста, улучшите – saeleko

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