简体   繁体   English

%在此C程序上如何工作? (奇数和偶数整数之和)

[英]How does % work on this C program? (sum of odd and even integers)

here's the code: 这是代码:

    #include <stdio.h>
#include <conio.h>
void main()
{
       int i, N, oddSum = 0, evenSum = 0;


printf("Enter the value of N\n");
    scanf ("%d", &N);
for (i=1; i <=N; i++)
      {
        if (i % 2 == 0)
            evenSum = evenSum + i;
        else
            oddSum = oddSum + i;
    }
printf ("Sum of all odd numbers  = %d\n", oddSum);
    printf ("Sum of all even numbers = %d\n", evenSum);

}

In this program it gets a number from user (N) and then prints sum of odd and even numbers in two different lines. 在此程序中,它从用户(N)获取一个数字,然后在两条不同的行中打印奇数和偶数之和。

two questions: 两个问题:

1- how does % work here? 1-%在这里如何工作? 2- explain this line completely: 2-完全解释这一行:

if (i % 2 == 0)
        evenSum = evenSum + i;

The % operator gives you the remainder of division. %运算符为您提供余数除法。

An even number divided by 2 will always have a remainder of 0 regardless of sign. 除以2,偶数除以2将始终具有0的余数。 Odd numbers, if positive will have a remainder of 1 and if negative will have a remainder of -1 . 奇数,如果为正数,则余数为1 ;如果为负数,则余数为-1 You only need to test a single case to determine if it is even however, and that is what you see happening in your existing code. 您只需要测试一个案例就可以确定是否成立,这就是您在现有代码中看到的情况。

It is more efficient to test the least significant bit to determine if a number is odd though: 测试最低有效位以确定数字是否为奇数会更有效:

if (i & 1)    // Example: 0101 (5) & 0001 (1) == 1
  // Odd

else          // Example: 0100 (4) & 0001 (1) == 0
  // Even

That approach does not involve division and only has two possible outcomes instead of three when dealing with signed integers. 该方法不涉及除法,在处理带符号整数时只有两个可能的结果,而不是三个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM