c - 有什么建议或改进吗?

标签 c loops for-loop do-while

我可以在这个程序中使用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”循环替换“do...while”循环效果不好。在第一个代码(for 循环)中,如果用户选择正确答案,程序将执行 5 次相同的操作。插入“do while”时,循环会在答案正确时停止(选择 is = 1...2....3...4..or 5)。我认为第二个代码是正确的 问候

关于c - 有什么建议或改进吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30102243/

相关文章:

c - 为什么 fread() 的第一个参数被强制转换为其他类型

c - 链接错误 - 使用 nm 修复

c - 将整个文本文件读入 C 中的 char 数组

python - 计算器输出错误答案

java - 如何编写使用 * 打印大写字母 F 的嵌套循环

c - LD_LIBRARY_PATH 被 GCC 忽略

c++ - 压缩嵌套循环

c - 给定迭代次数,如何检索双 for 循环的索引?

batch-file - 如何在for循环中处理路径名中的右括号?

r - r 中的索引,某些点的问题