1.因式分解
#include <iostream>
#include <math.h>
using namespace std;
bool IsPrime(int n);
void Resolve(int n);
int main()
{
int n;
cout<<"Input a integer num n(n>0):";
cin>>n;
if(n==1)
cout<<"1=1"<<endl;
else if(IsPrime(n))
cout<<n<<"="<<"1*"<<n<<endl;
else // >1 and not prime
Resolve(n);
cout<<endl;
return 0;
}
bool IsPrime(int n)
{
int k,i;
k=static_cast<int>(sqrt((double)n));
if(n==1)
return false;
for(i=2;i<=k;i++)
{
if(n%i==0)
break;
}
if(i>k)
return true;
else
return false;
}
void Resolve(int n)
{
int i;
cout<<n<<"=";
i=2;
while(1)
{
if(IsPrime(i)&&n%i==0)
{
cout<<i<<"*";
n=n/i;
}
else
i++;
if(n==1)
break;
}
}
2.函数返回类型为指针需要注意的问题
#include <stdio.h>
#include <string.h>
typedef struct student
{
char sex;
char name[10];
}stu;
char *get();
int main()
{
printf("1. %s\n",get());
printf("2. %s\n",get());
return 0;
}
char *get()
{
stu doctor;
doctor.sex='M';
strcpy(doctor.name,"wang");
//方法1:分配堆(由程序员自己释放),返回局部变量的地址
char *s;
int len=strlen((char *)&doctor);
s=new char[len+1];
strcpy(s,(char *)&doctor);
return s;
// return (char *)&doctor;
}
char *get()
{
static stu doctor;//方法2:申明为static类型,返回局部变量的地址
doctor.sex='M';
strcpy(doctor.name,"wang");
return (char *)&doctor;
}