c - 查找 C 中 N 个案例之间的偶数

标签 c int case intervals

我想编写一个代码,以便您找到 N 个案例(y)之间的所有偶数。接下来的 y 行将包含 n 个数字 (1<=n1<=100)。对于每一行,我想找到它们之间的偶数。例如:

input:
2 (number of cases; 1<=y<=10)
1
7
Output:
No even numbers
2 4 6

如果它们之间没有偶数,则打印“无偶数”,例如:

所以到目前为止我所做的是:

#include <stdio.h>
int main()
{
    int n1, n2, i, j, p, y;
    printf("number of intervals: ");
    scanf("%d", &y);
    for(j=1; j<=y; j++)
    {
        scanf("%d", &n1);
        for(i=1;i<=n1; i++)
        {
            p=i%2;
            if(p==0)
                printf(" %d", i);     
        }
        return 0;
    } 
}

问题是我不知道如何在代码中实现间隔数,它只适用于两个间隔。

最佳答案

如果您想使用不同的值执行类似的操作,那么创建一个函数总是一个好主意。您可以创建一个函数并根据需要多次调用该函数。例如

void printInterval(int n1, int n2){  //function will print all even 
    for(i=n1;i<=n2; i++)//number between n1 and n2 (both inclusive)
    {
        p=i%2;
        if(p==0)
        printf(" %d", i);   

    }
}

关于c - 查找 C 中 N 个案例之间的偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33227053/

相关文章:

c++ - 为什么强制int夸大性能问题?

带有 switch 语句的 C++ 逻辑

java - Switch 设置为 int 参数。创建默认情况以排除字符串,这样就不会读取错误

c - 静态存储在内存中的全局变量在哪里?

c - 显示带有特殊字符的字体 - UTF-8

C:将 int 转换为 String

c++ - 在 C++ 中将十六进制字符转换为 int

mysql - SQL - 对动态表使用案例语句(未知行数)

c - 从 RAM 执行代码时应该禁用中断吗?

c++ - 如何用C语言打印带有心形符号的M字符?