嵌套的if else语句给出不正确的结果而不运行

本文关键字:结果 运行 不正确 if else 语句 嵌套 | 更新日期: 2023-09-27 18:12:12

我正在尝试创建一个日志文件系统,其中包含索引。对于日志文件中的每100行,日志文件应该重新创建到log1.log,对于每创建1000个文件,index1.log应该重新创建到index2.log

if (timesrun % 100 != 0)
{
    Debug.Write(" enter code here. ");
    if (timesrun % 1000 != 0)
    {
        Debug.Write("'");
        Debug.Write(" enter code here. ");
     }
    else
    {
        Debug.WriteLine("rename files index?.xml ");
        string basename = "index";
        string extention = ".log";
        crntstmap++;
        nowsitemap = basename + crntstmap + extention;
        Debug.WriteLine(nowsitemap);
                        }
    //call method create actual file using the filename + timesrun IE
}
else
{
    Debug.WriteLine("rename files log?.php ");
    string basename = "log";
    string extention = ".log";
    crntindx++;
    nowindex = basename + crntindx + extention;
    Debug.WriteLine(nowindex);
}

我得到奇怪的结果,if循环的第二部分从未运行,我从未看到Debug.WriteLine(nowsitemap);

嵌套的if else语句给出不正确的结果而不运行

我不确定你到底想要完成什么,但执行从未进入该分支的原因是因为一个数字不可能不是100的倍数1000的倍数。1001000的因子。

if(timesrun % 100 != 0 && timesrun % 1000 == 0) // Always false
{
    Debug.WriteLine("rename files index?.xml ");
    string basename = "index";
    ...

基本上你的比较是反向的。:

if (timesrun % 100 != 0)

每100次运行99次,而每100次运行1次

你的意思:

if (timesrun % 100 == 0)

,同样地,对于1000例…虽然这将在每10文件中滚动文件,而不是每1000文件,因为您将在1000行之后执行此操作。您可以将其设置为100000,或者将其更改为每个行一个变量,每个文件一个变量。

(注意,如果您适当地排列缩进,您的代码结构也会清晰得多。)

因为if timesrun % 100 != 0所以timesrun % 1000总是会是not 0