【问题标题】:c - why is my for loop with a scanf not being executed? [closed]c - 为什么我的带有 scanf 的 for 循环没有被执行? [关闭]
【发布时间】:2018-09-14 08:28:15
【问题描述】:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char firstName1[20];
    char lastName1[20];
    char firstName2[20];
    char lastName2[20];
    char firstName3[20];
    char lastName3[20];


    int scores[18];

    scanf("%s", &firstName1[0]);
    scanf("%s", &lastName1[0]);

    printf("%s ", &firstName1[0]);
    printf("%s ", &lastName1[0]);

    //this for loop here is not being executed, could it be a formatting 
    issue? 
    //%i or %d?
    int i=0;
    for(i=0;i>6;i++)
    {
        scanf(" %d ", &scores[i]);
    }


    int j=0;
    for(j=0;j>6;j++)
    {
        printf("%i", &scores{j]);
    }

    return 0;
}

提供的图片显示输出结果,输入名称和打印名称有效,但没有执行scanf取分数的循环

The first part of the code taking in the name and printing it back works, however the rest of the code (being the for loops) are not being executed.

【问题讨论】:

    标签: c arrays for-loop scanf


    【解决方案1】:

    改变

     for(i=0;i>6;i++)
    

     for(j=0;j>6;j++)
    

     for(i=0;i<6;i++)
    

     for(j=0;j<6;j++)
    

    循环仅在条件为真时运行,并且在开始时i=0 所以i&gt;6 为假...或者用英文你写的方式循环运行,而 i 大于 6 - i 开始于0 所以它不会运行循环 - 你的下一个循环也有同样的问题。

    还有一些其他的事情——比如在第一个循环中我会写一行来说明

      printf("please enter score %d: ",i); 
    

    因为当您输入数字时它会更有意义,并且您会更好地看到发生了什么。

    下面的编辑代码.... ** 还要注意 &amp; 仅适用于 scanf 而不是 printf ** 请参阅下面的代码,它已在最终循环中为 printf 删除。

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main()
    {
        char firstName1[20];
        char lastName1[20];
        char firstName2[20];
        char lastName2[20];
        char firstName3[20];
        char lastName3[20];
    
    
        int scores[18];
    
        scanf("%s", &firstName1[0]);
        scanf("%s", &lastName1[0]);
    
        printf("%s ", &firstName1[0]);
        printf("%s ", &lastName1[0]);
    
        //this for loop here is not being executed, could it be a formatting 
        issue? 
        //%i or %d?
        int i=0;
        for(i=0;i<6;i++)
        {
            printf("please enter score %d: ",i);       
            scanf(" %d ", &scores[i]);
        }
    
    
        int j=0;
        for(j=0;j<6;j++)
        {
            printf("score %i: %i\n", j, scores{j]);
        }
    
        return 0;
    }
    

    【讨论】:

    • 没有意识到这个错误,谢谢!你能告诉我为什么分数被录入但打印不正确吗? tinypic.com/r/2nva5ag/9(不确定哪个链接有效)oi68.tinypic.com/2nva5ag.jpg
    • @William 是的 - 我应该已经发现了 - 我刚刚编辑了关于这一点的答案。 - 打印时不需要&amp;....&amp; 表示地址,scanf 需要它,而printf 只需要值,所以最后一行应该是printf("%i\n", scores{j]); \n 在每个得分后换行。
    • @chux - 感谢您的留言 - 我没有意识到礼仪。我不会再这样做了——除了要求人们接受其他人的答案以表明他们的问题已经解决,但这是不应该做的事情吗? p.s.我喜欢你的头像。 -- 可能我年纪小了点,ZX81开始写代码
    猜你喜欢
    • 1970-01-01
    • 2020-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多