简体   繁体   English

C ++所有素数函数都不起作用

[英]C++ all prime numbers function not working

So i am really new at programming, i was messing around and decided to try coding a Prime generator. 所以我真的很喜欢编程,我一直在搞乱,并决定尝试编写Prime生成器。 The idea is the user inputs the maximum number the computer should check for a prime, and it outputs a text file with all the primes till there. 这个想法是用户输入计算机应检查素数的最大数量,并输出一个包含所有质数的文本文件,直到那里。 So i've written this piece of code. 所以我写了这段代码。

#include <iostream>
#include <string>
#include <Windows.h>
#include <fstream>

using namespace std;
int isPrime(int num) {
    for (int a = 1; a <= num/2; a++) 
        if (num % a == 0)
            return 0;
    return 1;
}


int main() {
    ofstream out_data("primes.txt");
    std::string name;
    int quantity;
    int maximum = 1000000;
    std::cout << "What is your name ?\n";
    getline(std::cin, name);
    std::cout << "What is the biggest number you want to get as a prime " << name << "? Please note that the maximum is " << maximum <<" \n";
    std::cin >> quantity;
    if (quantity <= maximum) {
        for (int b = 1; b < quantity; b++) {
            if (isPrime(b) == 1) {
                std::cout << b << "\n";
                out_data << b << "\n";
            }
        }
        std::cout << "The computer has finished calculating primes. Please check your folder for a .txt file.";
        Sleep(60000);
    }
    if (quantity > maximum) {
        std::cout << "Oh, i'm sorry. The computer can not calculate till " << quantity << ".";
        Sleep(15000);
    }
    return 0;
}

The file and the console shows just the number 1. I spent some time trying to find out what's wrong with the code and got nowhere. 文件和控制台只显示数字1.我花了一些时间试图找出代码有什么问题而无处可去。 In my mind the for loop would repeat itself and the if statement until b 在我看来,for循环会重复自己和if语句直到b

You should start your loop in isPrime from 2 instead of 1 . 你应该从2而不是1开始在isPrime循环。 Every integer equals 0 mod 1 . 每个整数等于0 mod 1

I believe your issue lies within your isPrime funcion. 我相信你的问题在于你的isPrime功能。 The first iteration of the for loop when a = 1 will always catch the if statement due to any num % 1 = 0. Start your for loop with a = 2. 当a = 1时for循环的第一次迭代将始终捕获if语句,因为任何num%1 = 0.使用a = 2启动for循环。

   int isPrime(int num) {
        for (int a = 2; a <= num/2; a++) 
            if (num % a == 0)
                return 0;
        return 1;
    }

Since num / 2 = 0, the for loop is never entered when num = 1. Therefore, your isPrime() funtion will return 1 and it will let it output. 由于num / 2 = 0,因此,当num = 1时,永远不会输入for循环。因此,你的isPrime()函数将返回1,它将让它输出。 All other nums will enter the for loop and return 0. 所有其他nums将进入for循环并返回0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM