请澄清为什么我没有得到以下代码的输出。 [英] Please clarify me why I am not getting output for below code.

查看:72
本文介绍了请澄清为什么我没有得到以下代码的输出。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中找到一个元素是否存在于数组中,如果取消部分取消注释,我没有得到输出。



In the below code to find an element is present in an array or not,I am not getting the output if else part is uncommented.

#include<stdio.h>
int main()
{
    int a[]={2,5,8},i,n=2,flag=0;
     
        for(i=0;i<10;i++)
        {
            if(a[i] == n )
            {
                flag = 1;
            }
            //else 
              //  flag = 0;
        }
        if(flag==1)
                printf("present %d\n",n);
}





我的尝试:



如果其他部分被注释,我将得到输出。



What I have tried:

If else part is commented ,I am getting output.

推荐答案

简单:如果你取消注释该行,那么每次它都找不到匹配时,它将标志设置为不匹配。这意味着如果您在第一个位置找到匹配项,则设置找到它标志,并将其覆盖回数组中的每个其他字符的未找到。

最佳解决方案这很简单:当你找到匹配时退出循环:

Simple: if you uncomment the line, then every time it doesn't find a match, it sets the flag to "no match". Which means that if you find a match in the first location, you set the "found it" flag, and overwrite it back to "not found" for every other character in the array.
The best solution to this is simple: exit from the loop when you find a match:
int main()
    {
    int a[]={2,5,8},i,n=2
    for(i=0;i<10;i++)
        {
        if(a[i] == n )
            {
            printf("present %d\n",n);
            break;
            }
        }
    }


当存在else部分时,根据最后检查的项目设置标志。然后循环是不必要的,因为类似的检查将是:

When the else part is present the flag is set according to the last checked item. Then the loop is not necessary because a similar check would be:
if (a[9] == 2)
    flag = 1;
else
    flag = 0;


Writing it down this way you should also recognise that you are accessing items that are not part of the array (out of bound access) because your array has a size of three items so that the highest allowed index is two.


很明显,你的别名中的标志设置为0。当if语句失败时,它每隔一段时间就会发生。



你应该使用调试器!!!



And如果不清楚,请制作一些 TRACE 输出。
It is really obvious that the flag is set to 0 in your else. It happens EVERYTIME when the if statement fails.

You should use the debugger !!!

And make someTRACE output if something is unclear.


这篇关于请澄清为什么我没有得到以下代码的输出。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆