【问题标题】:C language: The Array did not return a correct valueC 语言:数组没有返回正确的值
【发布时间】:2018-11-22 12:55:12
【问题描述】:

我有一个 C 语言作业,要求用户向数组输入值。我的想法是创建两个不同的数组,一个包含整数值,另一个包含字符值。到目前为止,这是我的代码:

#include <stdio.h>

int main()
{
    char continued;
    int i = 0;
    char instrType[10];
    int time[10];

    printf("\nL-lock a resource");
    printf("\nU-unlock a resource");
    printf("\nC-compute");
    printf("\nPlease Enter The Instruction Type");
    printf(" and Time Input:");
    scanf("%c", &instrType[0]);
    scanf("%d", &time[0]);
    printf("\nContinue? (Y/N) ");
    scanf("%s", &continued);
    i = i + 1;

    while (continued == 'Y' || continued == 'y')
    {
        printf("\nL-lock a resource");
        printf("\nU-unlock a resource");
        printf("\nC-compute");
        printf("\nPlease Enter The Instruction Type ");
        printf("Time Input:");
        scanf("%c", &instrType[i]);
        scanf("%d", &time[i]);
        printf("\nContinue? (Y/N) ");
        scanf("%s", &continued);
        i = i + 1;
    }

    return 0;
}

期望值应该是:L1 L2 C3 U1 我的截图

当我尝试输入新值时,循环刚刚停止,即使我输入“Y”表示“是继续”,条件也没有检查该值,请帮助:(

【问题讨论】:

标签: c arrays


【解决方案1】:

您正在将字符串与一个字符进行比较,而不是使用 scanf("%s",&continued) 尝试使用 "%c"

【讨论】:

    【解决方案2】:

    主要问题是scanf("%c", &amp;char) 因为scanf() 在读取输入后打印\n 以传递到下一行,这导致下一个scanf() 不是读取您的输入,而是读取@987654325 @,导致读取输入失败。 为避免此问题,请在 %c 之前添加一个空格 ==> scanf(" %c", &amp;char)

    #include <stdio.h>
    
    int main()
    {
        char continued;
        int i = 0;
        char instrType[10];
        int time[10];
    
        do
        {
            printf("L-lock a resource\n");
            printf("U-unlock a resource\n");
            printf("C-compute\n");
            printf("Please Enter The Instruction Type and Time Input: ");
            scanf(" %c%d", &instrType[i], &time[i]);
            printf("Continue? (Y/N) ");
            scanf(" %c", &continued);
            i++;
        } while (continued == 'Y' || continued == 'y');
    
        return 0;
    }
    

    其他:

    你可以使用i++代替i = i + 1

    使用do{...}while() 来节省一些代码行,而不是使用while()

    您可以在一行中连接更多输入 ==> scanf(" %c%d", &amp;instrType[i], &amp;time[i])

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多