c++问题请帮忙

来源:百度知道 编辑:UC知道 时间:2024/06/10 02:26:47
比如我输入的是12 他的因数是 1 2 3 4 6 12 其中偶因数是 2 4 6 12
那么偶因数一共有4个 因数是6个 百分比就是(4/6)*100

搞不懂的是不知道怎么提取出偶因数的数量和因数的数量

请帮忙写出来

没调试,但思路是这样的,自己调一下吧,这个方法比较慢
void main()
{
int x=12;
int m=0,n=0;
for(int i=1;i<=x;i++)
{
if(x%i==0)
{
m++;
if(i%2==0)
n++;
}
cout<<n/m*100;
}

以下仅计算两者百分比,如果要提取出具体的因数,则需要使用动态int数组,虽然不麻烦,但在此就不写了。

代码如下,VC6+WinXP调试通过:

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

void main()
{
int num, total = 0, count = 0;
cout << "Enter a number: ";
cin >> num;
if( num<1 ) return;
for( int i = 1; i<= num; i++ )
if( num%i == 0 )
{
if( i%2 == 0 ) count ++;
total++;
}
cout << count << "/" << total << " = " << setiosflags(ios::fixed) << setprecision(2) << 100*count/total << "%" << endl;
}