質問

I've got the following function in C++:

#include <iostream>
#include <cmath>
#include <stdlib.h>    
bool isPrime(char myArr[])
{
    int myInt=atoi(myArr);
    int maxX=sqrt(myInt)+1;
    for(int x=0; x<maxX; x++)
    {
        if(!myInt%x)
            return false;
    }
    return true;
}

But when I run it, Windows returns with a message box saying "Prime.c has stopped working" I have a feeling it's got something to do with the use of atoi though I'm not sure. Should atoi be used? Am I using it wrong? Or is it an entirely different problem?

Thanks

役に立ちましたか?

解決

You don't have a problem with atoi specifically, though you aren't checking to see if it worked correctly.

The real problem is that your program divides by zero on the first iteration of the loop. Start x at 2:

for (int x = 2; x < maxX; x++)

You do have to start at 2, too. Starting at 1 will tell you that all of your numbers are prime, which isn't true and probably isn't what you want. You might need a special case to handle 0 and 1 inputs - they're not prime, but will fall out of your current algorithm.

Editorial aside: There are plenty of faster ways to check if a number is prime, if that's of use to you.

他のヒント

You don't want to divide by 0, start at 2:

for (int x = 2; x < maxX; x++)
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top