C 语言程序:查找在一个范围内可被 5 整除的数字之和及总数


2023 年 10 月 22 日, Learn eTutorial
3099

一个数字或整数如果能被 **5** 或任何其他数字“**n**”**整除**,则表示该除法操作的**余数**为 **0**。

如何在一个给定范围内查找可被 5 整除的数字及其总和?

为了确定给定范围内所有可被 5 整除的数字,我们**取该范围内的每个数字并计算该数字模 5**。除法后,如果余数为零,则该整数可被 5 整除。然后我们将该整数加到**和变量**中并递增**计数**。

让我们以“**5、10、15**”为例。对这些数字与 **5** 进行**模**运算,如果余数为零,则该数字可被 5 整除。**同样的逻辑可以应用于检查任何数字的整除性。**

简单程序: C 语言程序:检查一个数字是否可被 5 整除

我们如何使用 C 语言程序应用数字整除性逻辑?

这是一个 C 语言程序,我们将变量 **count**、**Sum** 等声明为整数。现在我们打开一个从下限到上限值的“for 循环”,这些值是从用户那里接收的。在“for 循环”内部,我们取每个数字并进行**模**运算;如果余数为**零**,则将 **count** 增加**一**,并将 **Sum** 等于 **Sum + 该整数**。 将其打印为可被五整除的整数。

算法

步骤 1: 包含头文件以包含在 C 语言程序库中定义的内置函数库。

步骤 2: 使用 main() 函数开始程序执行。我们将主函数定义为操作 Void,这意味着没有返回值。

步骤 3: 使用 int 数据类型声明并初始化变量。

步骤 4: 使用 printfscanf 接受用户输入的下限和上限值。

步骤 5: 使用“for 循环”从下限到上限递增 **1**,以检查每个元素是否是 **5** 的除数。

步骤 6: 使用“if”条件检查整数 **Mod 5** 是否为**零**。

步骤 7: 如果余数为**零**,则将计数递增**一**,并打印该整数为 **5** 的除数。

步骤 8: 在循环的每次迭代中将该数字添加到 **Sum** 中。

步骤 9: 使用 printf 打印 **Sum** 和数字以及计数。


为了检查数字整除性程序,我们使用了以下 C 语言主题,我们建议学习这些主题以更好地理解

C 语言源代码

                                          #include <stdio.h>


void main()
{
   int i, N1, N2, count = 0, sum = 0;                          /* declares count, sum and two variables as integer */
   printf("Enter the value of N1 and N2\n");              /* user gives the value for lower and upper range */
   scanf("%d %d", & N1, & N2);
   printf("Integers divisible by 5 are\n");                   /*Count the number and compute their sum*/
   for (i = N1; i < N2; i++) 
   {
      if (i % 5 == 0) 
      {
         printf("%d,", I);                    /*using mod operator check the number is divisible by 5*/
         count++;
         sum = sum + I;                    /*add the numbers divisible by 5 to sum variable*/
      }
   }
  printf("\nNumber of integers divisible by 5 between %d and %d = %d\n",
    N1, N2, count);
  printf("Sum of all integers that are divisible by 5 = %d\n", sum);              /* displays the output of program */
} 
                                      

输出

Enter the value of N1 and N2
2
27

Integers divisible by 5 are
5, 10, 15, 20, 25,

Number of integers divisible by 5 between 2 and 27 = 5
Sum of all integers that are divisible by 5 = 75