Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

C Program to find prime number

Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.

EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.

EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING

#include <stdio.h>
#include <math.h>

int prime(int a){
    int b;

    for(b=1; b<=a; b++){
        if (a%b==0)
        return(0);
    }
    if(b==a){
        return(1);
    }
}
int main(void){

    int c, answer;

    printf("Please enter the number you would like to find is prime or not= ");
    scanf("%d",&c);

    answer = prime(c);

    if(answer==1){
        printf("%d is a prime number 
",c);
    }
    else
        printf("%d is not a prime number
",c);
    }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

1. You never initialized i (it has indeterminate value - local variable).

2. You never call function is_prime.

And using a loop will be good idea .Comparing to what you have right now.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...