c++ - while(n--) 和 while(n=n-1) 有什么区别?

标签 c++ c

while(n--)while(n=n-1) 有什么区别?当我在代码中使用 while(n=n-1) 时,我可以输入少于 1 个数字。

示例:首先输入 3,然后输入 3 次单个数字(但在 while(n=n-1) 中不会发生这种情况)。 但是当我使用while(n--)时,就正常了。

我的代码是:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int n;
    long long inum;
    scanf("%d", &n);
    while(n--)
    {
        scanf("%lld", &inum);
        if(inum == 0 || inum % 2 == 0)
        {
            printf("even\n");
        }

        else
        {
            printf("odd\n");
        }
    }

    return 0;
}

最佳答案

n--的值是n的前一个值

int n = 10;
// value of (n--) is 10
// you can assign that value to another variable and print it
int k = (n--);                     // extra parenthesis for clarity
printf("value of n-- is %d\n", k);

n = n - 1 的值比 n 的前一个值小 1

int n = 10;
// value of (n = n - 1) is 9
// you can assign that value to another variable and print it
int k = (n = n - 1);                     // extra parenthesis for clarity
printf("value of n = n - 1 is %d\n", k);

关于c++ - while(n--) 和 while(n=n-1) 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33655155/

相关文章:

c++ - 一个类对象到另一个数据类型?

c - 获取最高有效半字节,无论 int 位长度和字节顺序如何

c - udp 连接套接字上的 ICMP "destination unreachable"数据包

c - C 中的 Trie 树上的段错误和 Valgrind 未堆叠地址错误

c - 如何使用c获取站点ip地址

c - C 中 mktime 的不一致结果

c++ - 类划分头文件和定义文件

c++ - Xcode 7 调试器不会中断内联 header 函数

c++ - 如何使用 RcppArmadillo 找到一个 vector 中元素的索引,这些元素也在另一个 vector 中?

c++ - 定义函数的引用目的