有什么建议或改进吗?

Any suggestions or improvements?

我可以用for循环代替这个程序中的do...while循环吗?有什么建议可以使这个程序更简单吗?该程序要求用户输入从 1 到 5 的选项(如果选择的是另一个数字,程序将终止) 我的代码:

int choice;
    char option;
    printf("You want to know what I'm thinking about you?\n");
    printf("1. Add New Contact\n");
    printf("2. Edit Existing Contact\n");
    printf("3. Call Contact\n");
    printf("4. Text Contact\n");
    printf("5. Exit\n");

for (int i = 0; i < 5; i++)
{
    printf("Please choose the above option:\n");
    scanf(" %d", &choice);
    switch (choice)
    {
    case(1) : printf("To add new contact, you need the contact's: First name, Last name and Number");
        break;
    case(2) : printf("To edit, enter new contact's number");
        break;
    case(3) : printf("Who do you wish to call");
        break;
    case(4) : printf("Who do you want to text");
        break;
    case(5) : exit(1);
    default: printf("\n%d is not a valid choice!\n", choice);
        break;

源代码:

do
{
printf("Enter your choice: ");
scanf(" %d", &choice);
switch (choice)
{
case (1): printf("\nTo add you will need the ");
printf("contact's\n");
printf("First name, last name, and number.\n");
break;

case (2): printf("\nGet ready to enter the name of ");
printf("name of the\n");
printf("contact you wish to change.\n");
break;
case (3): printf("\nWhich contact do you ");
printf("wish to call?\n");
break;
case (4): printf("\nWhich contact do you ");
printf("wish to text?\n");
break;
case (5): exit(1); //Exits the program early
default: printf("\n%d is not a valid choice.\n", choice);
printf("Try again.\n");
break;
}
} while ((choice < 1) || (choice > 5));
return 0;

好吧,理论上你可以,但这没有任何意义。根据经验:

  • 当迭代次数已知时使用for。 (通常被认为最容易阅读并且通常会生成最有效的代码。)
  • 迭代次数未知时使用while
  • 当迭代次数未知时使用do while,但必须将循环条件放在循环的第一圈之后(例如因为需要评估用户输出)。

恐怕没有。由于代码是当前编写的,主要的行为差异,除非输入是 5

  • for循环版本保证执行5次,
  • do...while 版本取决于每次迭代的输入值。对于任何小于 1 或大于 5 的值都将终止循环。否则,它将继续循环。

对于这个问题,我认为用 "for" 循环替换 "do...while" 循环不是很好。在第一个代码(for 循环)中,如果用户选择了正确答案,程序将进行 5 次相同的操作。 Insted 在 "do while" 中,当答案正确时循环停止(选择 = 1...2....3...4.. 或 5)。我认为第二个代码是正确的 问候