有人能告诉我这个c++代码出了什么问题吗?找不找素数
Can anyone Tell me whats wrong in this c++ Code - to find prime number or not
这是一个程序,用于查找输入的数字是否为素数。没有错误,但我总是得到答案,因为它不是任何数字的素数。
#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 scope
和error: ‘cin’ was not declared in this scope
cout
和cin
是在包含的iostream
标头中定义的函数。但是,这些是在std
命名空间中定义的,因此在全局范围中不可用。因此,要么使用std::cout
和std::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既不是素数也不是复合的,所以从技术上讲,在这种情况下你是不正确的
相关文章:
- 警告处理为错误这里有什么问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 当我尝试添加 2 个大字符串时,我无法弄清楚出了什么问题
- 违反const正确性:我应该现实地期待什么问题
- 这个带有模板<类 Vector 的C++代码片段有什么问题>
- 我的逻辑反转字符串中的元音有什么问题?
- 需要以下代码的帮助,下面的代码有什么问题
- 常量公共成员有什么问题?
- c++无值sort()的问题是什么?
- 以下代码中的函数模板有什么问题?
- 这个返回元素位置的基于循环的函数有什么问题?
- creat_list2功能有什么问题?
- 基本的 c++ 问题:如果我在函数中创建某些内容并返回它会发生什么?
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 什么是钻石问题?是一系列问题还是特定问题?
- 格式说明符C++有什么问题
- 我应该在 main 函数中写什么来测试我的问题?
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 方法问题 - 什么会改变值,什么不会改变?什么是无效的?