gpt4 book ai didi

质因数的 C++ 程序

转载 作者:行者123 更新时间:2023-11-28 02:20:09 25 4
gpt4 key购买 nike

我正在尝试构建一个程序,要求用户输入一个正整数,然后输出该数字的质因数。我给用户三次尝试输入有效输入或程序结束。所以任何负整数和非整数以及其他字符如字母都会给出错误信息。我快到了,但我的输出不会如我所愿。它将小数视为整数,负数不会返回错误。

#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;
}

最佳答案

您不会因输入负数而收到错误消息,因为您没有在输入验证中检查负数。您可以添加到 while 条件中以检查负输出:

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

您没有捕捉到十进制数输入的原因是 cin 成功地将输入转换并存储到小数点,然后停止,将输入的其余部分留在缓冲区中。我们可以看到:

#include <iostream>

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

输入:

5.82

输出:

5
0.82

Live Example

您可以在 while 循环条件中包含一个检查,以查看是否有更多输入在流中等待

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

至于只循环三次,您可以在程序中添加一个计数器,并在每次循环体执行时递增计数器。一旦计数器达到 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++;
}

关于质因数的 C++ 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32827631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com