有人能告诉我这个c++代码出了什么问题吗?找不找素数

Can anyone Tell me whats wrong in this c++ Code - to find prime number or not

本文关键字:问题 什么 告诉我 代码 c++      更新时间:2023-10-16

这是一个程序,用于查找输入的数字是否为素数。没有错误,但我总是得到答案,因为它不是任何数字的素数。

#include<iostream.h>
#include<conio.h>
void main()
 { clrscr();
   int n,count = 0,i; 
   cout<<"enter the number n";
   cin>>n;
   for(i=1;i<=n;i++){
      if(n%i==0)
         count++;
   }
   if(count==2){
     cout<<"It is a prime number";}
   else {
     cout<<"It is not a prime number";}
   getch();
   }  

当程序编译失败时,编译器通常会向您提供有关代码问题的信息。您应该使用这些信息来跟踪问题,或者至少让那些寻求建议的人知道。

让我们一步一步地检查编译错误:

#include<iostream.h>

使用#include <iostream>代替

void main()

main应返回int。因此,将主入口点更改为:int main(int argc, char* argv[]),并在main函数的末尾添加一个return 0;

‘cout’ was not declared in this scopeerror: ‘cin’ was not declared in this scope

coutcin是在包含的iostream标头中定义的函数。但是,这些是在std命名空间中定义的,因此在全局范围中不可用。因此,要么使用std::coutstd::cin,要么在main函数之前放一个using namespace std;

有了这些更改,代码编译得很好,并且似乎产生了正确的输出。

@Neeraj Karthikeyan你的for循环,如果条件不正确,这就是为什么你每次都没有得到素数,试着理解下面的代码

#include <iostream>
#include<conio.h>
void main()
{
  int n, i, flag=0;
  clrscr();
  cout << "Enter a positive integer: ";
  cin >> n;
  for(i=2;i<=n/2;++i) //start i with 2 because if you start with 1 so all number will divisible by 1.
  {
      if(n%i==0)//if this is true it means number is not prime number
      {
          flag=1; //here we assign 1 in flag and breaking this block.
          break;
      }
  }
  if (flag==0) // if n did not divisible by any number that means flag is still 0 
      cout << "This is a prime number";
  else //this means flag!=0 that means it divided by any number above therefore it is not a prime number
      cout << "This is not a prime number";
}

关于原始代码:我现在记不起运算符优先级,但它可能将循环条件计算为"n%(I==0)"。尝试使用括号,即"(n%i)==0"。否则代码在我看来是正确的。

@BunkerBoy:给定的算法试图计算n有多少除数,包括1和n-。如果恰好为2,则素数。你的方法将1分类为素数,但现在数学家通常将1既不是素数也不是复合的,所以从技术上讲,在这种情况下你是不正确的