请问c语言程序设计中这一部分是什么意思?

2025-03-13 18:01:00
推荐回答(1个)
回答1:

这是一个检查x是否为素数的函数,x就是需要检查的数字参数,x%i==0是x对i取余,然后判断余数是否等于0,等于0即存在整除,让flag=0,退出循环,不是素数。如果for循环完后flag仍为1,即不存在整除,则为素数。我给你个示例,稍有改动,原理一样:

#include "stdafx.h"

#include

using namespace std;


bool isp(int x)

{

for (int i = 2; i <= sqrt(x); i++)

{

if (x%i == 0)

return false;

}

return true;

}


int main()

{

int n;

cout << "请输入一个整数:" << endl;

cin >> n;

while (n)

{

if (isp(n))

cout << n << "是素数" << endl;

else

cout << n << "不是素数" << endl;

cin >> n;

}

system("pause");

    return 0;

}