我想问用户一个整数,并打印素因数。示例:用户输入100,程序显示2 2 5 5
到目前为止,我有以下内容:
#include <iostream>
using namespace std;
void factors(int n){
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
cout << z;
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{cout << n << "\n";}
}
int main()
{
int x;
cout << "Input positive integer greater than 1: ";
cin >> x;
factors(x);
cout << "The result: " << x;
return 0;}
我的问题是如何使我的主要职能与因素程序进行沟通。我运行该程序,收到要求输入的消息,输入12,得到消息“结果”,但有25个数字,还有12个用户输入的数字。就像程序正在避免我的factor(int n)程序一样。请帮助语法?!?
我的问题是我认为的语法。因为我找到了以下功能来帮助列出主要因素:查找主要因素-user44810
define factors(n)
z = 2
while (z * z <= n)
if (n % z == 0)
output z
n /= z
else
z++
if n > 1
output n
谢谢!!!
因此,最大的问题是因素功能的末尾缺少括号。您需要在if(n> 1)大括号之后添加另一个大括号。另外,最后一个cout的末尾缺少分号,这将引发错误。
另一个不会阻止代码运行的问题是,当您打印“结果:” << x时,您将得到与用户输入相同的值。
如果您希望主函数从该位置打印出factors()的结果,则该函数需要返回数据而不是打印数据。为了解决这个问题,可以使factors函数返回带有所需输出的字符串:
//return a string with the output
string factors(int n){
//create a string to save the output to
string factorlist = "";
int z = 2;
while (z * z <= n)
{
if (n % z == 0)
{
//append z to the end of the string and add a space to make it easier to read
factorlist+=to_string(z)+" ";
n = (n / z);
}
else
{
z++;
}
}
if (n > 1)
{
//append n to the end of the string and add a newline
factorlist+=to_string(n)+"\n";
}
//output the string factorlist to wherever the function was called from
return factorlist;
}
然后在看起来像这样的行上:
factors(x);
cout << "The result: " << x
应该:
cout << "The result: " << factors(x);
当前,您只是打印出用户输入的x值。如果要保存factor(x)的值,则需要设置一个与其相等的变量,如下所示:
string FactorsResult = factors(x)
然后打印;或者,如上面的更正代码所示,只需直接在cout语句中将其打印出来即可。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句