#C++初学记录(素数判断)

练习题目二
素数判断
A prime number is a natural number which has exactly two distinct natural number divisors: 1 and itself. For example, the first four prime numbers are: 2, 3, 5 and 7.

Write a program which reads a list of N integers and prints the number of prime numbers in the list.

Input
The first line contains an integer N, the number of elements in the list.

N numbers are given in the following lines.

Output
Print the number of prime numbers in the given list.

Constraints
1 ≤ N ≤ 10000

2 ≤ an element of the list ≤ 108

Sample Input 1
5
2
3
4
5
6
Sample Output 1
3
Sample Input 2
11
7
8
9
10
11
12
13
14
15
16
17
Sample Output 2
4

运行代码

#include<iostream>
using namespace std;
int main()
{
    int n;
    cin>>n;
    int b=0,m,count;
    for(int i=0;i<n;i++){
        cin>>m;
        count=1;
    for(int i=2;i<m;i++)
    {
        if(m%i==0)
        count=0;
        break;
    }
    if(count==1&&m!=1)
    b++;
    }  
    cout<<b;
    return 0; 

}
    

题目思考
所谓素数既是定义为在大于1的自然数中,除了1和它本身以外不再有其他因数。所以我使用嵌套循环,使他除以2到自己本身减1的所有数,若都除不尽,则素数数量+1,。
错误及调试
第一次编写好程序进行运行,运行结果出错如图。
1498728-20190319182532076-478559273.png
所以我进行调试,在调试过程中,我发现不论if里的条件成立与否,break都会运行,所以导致程序出错,调试如图。
1498728-20190319182718113-2012744125.png
所以,错误原因既是在if后,没有打出{ }导致if条件只对第一条代码生效,因此我修改代码后,程序运行正确。
1498728-20190319182837265-349995149.png

转载于:https://www.cnblogs.com/xiaofengqaq/p/10554935.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值