循环条件问题(for) [英] Loop condition problem (for)

查看:61
本文介绍了循环条件问题(for)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我试图从循环中走出来,当我的字符串= 0(flase)但是由于某种原因它不起作用。

这是我的功能:

Hi guys
im trying to go out from the loop when my string=0(flase)but from some reason it dosn''t work.
this is my function:

int getArchiveLength(char * str)
{
    int sc,i,count=1,len=1,res;
    for(sc=0,i=1;str[sc];sc++,len++)
    {
        while(str[sc]==str[sc+i]) count++,i++;
        if(count>=9)
        {
            res=count/9;
            len=((res*2)+1);
        }
        else
            len++;
        sc+=i; count=0;
    }
    return len;
}

推荐答案

Quote:

while(str [sc] == str [sc + i])count ++,i ++;

while(str[sc]==str[sc+i]) count++,i++;



如果找不到匹配项,则增加两次 sc (因为 1 )。

我想


When a match is not found, you increment twice sc (because i is 1).
I suppose

sc+=i-1;



(而不是 sc + = i; )会修复它。)


这里有几个问题:



i 仅在for循环开始时初始化一次。但它应该在里面循环初始化。



res 正在设置中,但从未使用过。



len 计算错误。即使是空字符串,也会返回值为1。



您现在第二次粘贴此代码。相反,您应该使用调试器并逐步执行代码,正如我之前已经建议的那样。如果您认为自己可以在不学习如何使用调试器的情况下离开,那么您将无法在软件开发方面取得进展。一些建议:单步执行每一段新代码,看看是否一切都按预期工作!
There are several things wrong here:

i is initialized only once at the start of the for loop. But it should be initialized inside the loop.

res is being set, but never used.

len is being calculated wrong. Even for an empty string a value of 1 is being returned.

You are pasting this code now for the second time. Instead, you should use a debugger and step through your code, as I have recommended already before. If you think you can get away without learning how to use a debugger you won''t get far in software development. Some advice: Single-step through every new piece of code to see if everything is working as expectedly!


直截了当地说:这段代码是废话。



我的建议:

To state it bluntly: this code is crap.

My advise:


  1. 在评论中描述函数的目的是计算什么(似乎有些长度编码压缩算法,但目前尚不清楚如何exaclty)
  2. 使所有块 {...}
  3. 做不依赖于逗号运算符(使用; - 参见上面的2.)
  4. 仅在一个地方而不是在多个地方修改迭代变量( sc,i,len,res,len
  5. 进行一致的初始化(例如,不清楚为什么最初 count = 1 以后再做 count = 0 等。)

  1. describe in a comment what the function aims to calculate (it seems to be some length encoding compression algorithm, but it''s not clear how exaclty)
  2. make all blocks { ... }
  3. do not rely on the comma operator (use ; - see 2. above)
  4. modify the iterating variables only at one place and not at several places (sc, i, len, res, len)
  5. do consistent initialisation (e.g. not clear why initially count = 1 and later you do count = 0 etc.)





尝试描述函数,定义一些单元测试,最后正确地重新实现它。



干杯

Andi



Try to describe the function, define some unit tests and finally properly re-implement it.

Cheers
Andi


这篇关于循环条件问题(for)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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