简体   繁体   English

素数C ++程序

[英]C++ Program for Prime Factors

I'm trying to build a program that asks to user to input a positive integer and then the prime factors of this number are outputted. 我正在尝试构建一个程序,要求用户输入一个正整数,然后输出该数字的素数。 I'm giving the user three attempts to enter a valid input or the program ends. 我为用户提供了三种尝试输入有效输入或程序结束的尝试。 So any negative integers and non integers as well as other characters such as letters will give an error message. 因此,任何负整数和非整数以及其他字符(例如字母)都将给出错误消息。 I'm nearly there but my output won't behave as I want. 我快到了,但是我的输出不会达到我想要的状态。 It treats decimal numbers as integers and negative numbers aren't returning the error. 它将十进制数视为整数,负数不返回错误。

#include <iostream>
#include <iomanip>
#include <cmath>
#include <stdio.h>

using namespace std;

int main()
{
    int num,i,flag,n;



    //executes loop if the input fails (e.g., no characters were read)
    while (cout << "Enter a number: " && !(cin >> num)) 
    {
        cin.clear(); //clear bad input flag
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); //discard input
        cout << "Invalid input, please re-enter: \n";
    }

    i=2;
    n=num;
    cout<< "\nThe Prime factors of "<< num << " are:"<< endl;
    while(i<=num)
    {
        flag=0;
        while(n%i==0)
        { 
            n=n/i;
            flag++;
        }
        if(flag>0)
        {
            cout <<i<< endl;
        }
        ++i;
     }


     system("PAUSE");
     return 0;
}

You are not getting an error for entering a negative number as you are not checking for that in you input validation. 输入负数不会出错,因为您不会在输入验证中检查该数字。 You could add into your while condition to check for a negative output as: 您可以添加到while条件中,以检查是否为负输出,如下所示:

while (cout << "Enter a number: " && (!(cin >> num) || num <= 0)) 

The reason you do not catch input of a decimal number is cin successfully converts and stores the input up to the decimal point and then stops, leaving the remainder of the input in the buffer. 您没有捕获十进制数字输入的原因是cin成功地转换了输入并将其存储到小数点,然后停止,从而将输入的其余部分保留在缓冲区中。 We can see that with: 我们可以看到:

#include <iostream>

int main() 
{
    int foo;
    double bar;
    std::cin >> foo;
    std::cin >> bar;
    std::cout << foo << std::endl;
    std::cout << bar;
}

Input: 输入:

5.82

Output: 输出:

5
0.82

Live Example 现场例子

You could include a check in your while loop condition to see if there is more input waiting in the stream with 您可以在while循环条件中添加一个检查,以查看流中是否还有更多输入在等待

while (cout << "Enter a number: " && (!(cin >> num) || num <= 0 || cin.get() != '\n'))

As for looping only three times you can add a counter to the program and increment the counter each time the body of the loop executes. 至于仅循环三次,您可以在程序中添加一个计数器,并在每次循环主体执行时递增该计数器。 Once the counter gets to 3 then you would exit the program 一旦计数器达到3,您将退出程序

int counter = 0;
while (cout << "Enter a number: " && (!(cin >> num) || num <= 0 || cin.get() != '\n'))
{
    if (counter == 3)
        return 0;  // exit
    cin.clear(); //clear bad input flag
    cin.ignore(numeric_limits<streamsize>::max(), '\n'); //discard input
    cout << "Invalid input, please re-enter: \n";
    counter++;
}

!(cin >> num) is only true when cin fails to insert the input character data into num, which is an int . !(cin >> num)仅在cin无法将输入字符数据插入num时才为true,num是一个int Both negative integers (like -12) and decimal quantities (like 3.14) can be stuffed into a signed int . 负整数(例如-12)和十进制数量(例如3.14)都可以填充到有符号的int The decimal quantity works because float s can be coerced into int s by truncation. 十进制数量有效,因为float可以通过截断被强制转换为int

To do what you want, you need to first capture your console input as a string, then attempt to parse out a positive integer. 要执行所需的操作,首先需要将控制台输入捕获为字符串,然后尝试解析出正整数。 Take a look at How do I check if a C++ string is an int? 看一看如何检查C ++字符串是否为int? and also boost::lexical_cast (if boost is an option). 以及boost::lexical_cast (如果可以选择boost)。

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

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