使用if语句的函数

时间:2012-04-18 23:39:23

标签: c

嗨,我是编程新手。我知道函数是如何工作的以及if语句,所以我想知道如何编写if&函数中的else语句,将显示用户的答案。可能没有任何goto语句

代码如下:

  if(year < 1583) //considers if a year input is less than 1583 which is the starting year for this calendar
  {
       printf("\n\nPlease select a year after 1583 \n\n");
       goto YEAR;
       system("cls");
  }
  if(Leap_year(year))//if statement calls Leap Year function
  {
       printf("\t =======================  \n");
       printf("\t*  THIS IS A LEAP YEAR  *\n");      
       printf("\t =======================  \n\n"); 
  }
  else {
       printf("\t   =======================  \n");
       printf("\t*  THIS IS NOT A LEAP YEAR  *\n");
       printf("\t   =======================  \n\n"); 
  }

3 个答案:

答案 0 :(得分:2)

无论是C还是C#,您都可以使用while循环解决此问题。

do
{     
      // You need to prompt for year here.  Your code doesn't show how you do that.
      if (year < 1583)
      {
          printf("\n\nPlease select a year after 1583 \n\n");
          // Note: The user will never see the printf above if you clear the screen right after
          system("cls");
      }
} while (year < 1583);

答案 1 :(得分:1)

您正在寻找的解决方案是使用更多功能。

考虑:

// year == -1 means there was an error
int year = -1;
while (year != -1)
{
  PromptForYear();
  year = GetYear();
}

此代码适用于GetYear,如下所示:

int GetYear()
{
  int year;
  cin >> year;

  // check for bad year values
  if (year < 1583)
    return -1;

  return year;
}

PromptForYear可能是

void PromptForYear()
{
  cout << "\n\nPlease select a year after 1583 \n\n";
}

我个人更喜欢TryGetYear方法:

while (true)
{
  PromptForYear();
  if (TryGetYear(&year))
  {
    break;
  }
}

// code for TryGetYear

bool TryGetYear(int* year)
{
  if (year == null)
    return false;

  cin >> *year;
  if (*year < 1583)
    return false;

  return true;
}

答案 2 :(得分:0)

删除goto - 添加其他

  if(year < 1583) //considers if a year input is less than 1583 which is the starting year for this calendar 
  { 
          printf("\n\nPlease select a year after 1583 \n\n"); 
          system("cls"); 
  } 
  else
  { 
....