【问题标题】:How to resolve the situation with n if and n || in C?如何解决 n if 和 n 的情况 ||在 C?
【发布时间】:2022-01-25 01:26:14
【问题描述】:

我正在学习 C 编程语言,我尝试解决 temp 可能从 1 到 n 并且我不能使用 n if 语句的情况,并且我不知道如何使用 for 或 a同时。

for (i=0;i<(count-1);i++) {
        if (flag == false) {
                if (temp == 1) {
                        if (i == (count - 2)) {
                                printf("%s", s1);
                        } else {
                                printf("%s",s2);
                        } 
                }

                if (temp == 2) {
                        if (i == (count - 3) || i == (count - 2)) {
                                printf("%s", s1);
                        } else {
                                printf("%s",s2);
                        } 
                }

                if (temp == 3) {
                        if (i == (count - 4) || i == (count - 3) || i == (count - 2)) {
                                printf("%s", s1);
                        } else {
                                printf("%s",s2);
                        } 
                }

                ...

                if (temp == n) {
                        if (i == (count - n+1) || i == (count - n) || ... || i == (count - 2)) {
                                printf("%s", s1);
                        } else {
                                printf("%s",s2);
                        } 
                }

        } else {
                printf("%s",s2);
        }
}

所以 temp 可以是从 1 到 n,并且 temp 总是小于 count。 temp 不能为 0,因为在这种情况下 flag 为真。

我怎样才能让这段代码使用一段时间?谢谢!

【问题讨论】:

  • 您需要检查i是否介于count - 1 - tempcount - 2之间,并且只需要检查一次。

标签: c for-loop if-statement while-loop


【解决方案1】:

您缺少关于何时以及设置了哪些值 temp 的任何信息,因此我不知道您打算如何将其集成到循环中。不过,您当然可以做的是用更适合整个范围的比较来替换所有那些ifs(旁注:无论如何,switch 块会更可取):

if(count - temp - 1 <= i && i <= count - 2)

假设 temp 在这里是积分...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 2021-12-10
    • 2015-08-24
    • 2022-01-07
    • 2020-11-26
    • 2013-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多