0

Hi I am new in the programming. I know how a function works and if statement, so I want to know how would I be able to write an if & else statement in a function and would display the answer to the user. there may not be any goto statements

The code is as follows:

  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"); 
  }
4

3 回答 3

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);
于 2012-04-18T23:45:05.663 回答
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;
}
于 2012-04-18T23:50:47.427 回答
0

删除goto- 添加一个 else

IE

  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
  { 
....
于 2012-04-18T23:46:24.297 回答