开发者社区> 问答> 正文

用C编写一个程序,以显示两个自然数之间的所有现有质数[保持中]

用C编写一个程序,以显示要输入的两个自然数之间的所有现有质数,并定义一个封闭范围,即输入的数字包括在该范围内。

main ()
{
    int R, CR, i, a, N;
    for (i=0;1<10;i++){
        printf("\nENTER NUMBER: ");
        scanf("%i",&N);
        if (N<0){
        printf("\nINVALID NUMBER!");
    }
        CR=0;
        for (a=1;a<=N;a++){
            R=N%a;
            if(R==0) CR=CR+1;
        }
        if(CR==2) printf("\n%2.i It's Cousin", N);
        else printf("\n%i NOT COUSIN");
    }

system ("pause");
}

我该怎么做?

输入的数字必须是整数,程序应测试输入的每个数字是否大于0。如果输入的数字不满足此条件,则应循环到数字

始终按传入顺序和显示结果在屏幕上显示显示的消息

展开
收起
kun坤 2019-11-29 11:16:16 400 0
1 条回答
写回答
取消 提交回答
  • #include<stdio.h>
    
    int main(void)
    {
        int a, b;
        //takes the two input numbers
        printf("Enter the two numbers\n");
        scanf("%d %d", &a, &b);
        //checks if the entered number is invalid
        if((a < 0) || (b < 0))
        {
            printf("Invalid numbers");
            return -1;
        }
        //for each number between a and b, checks either it is prime or not
        for(int i = a; i <= b; i++)
        {
            int count = 0;
            //counts the number of divisors of the number i with remainder 0
            for(int j = 1; j <= i; j++)
            {
                if(i % j == 0)
                {
                    count++;
                }
            }
            //if number of divisors of the i is less than 3, which means the 
            //number is prime, it prints the number
            if(count < 3)
            {
                printf("%d ", i);
            }
        }
        return 0;
    }
    
    
    2019-11-29 11:16:28
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载