Gargan 于 2016.04.10 21:39 提问

#define _CRT_SECURE_NO_WARNINGS
#include
#include
using namespace std;
class Fraction
{

private:
int num, den;
public:
Fraction(char s[10]);
void set(int n, int d){ num = n; den = d;normalize(); }
int get_x(){ return num; }
int get_y(){ return den; }
private:
void normalize();
int lcd(int a,int b);
};

int main()
{
Fraction p3("12,14");
cout << p3.get_x() << endl;
cout << p3.get_y() << endl;
system("pause");
return 0;
}
Fraction::Fraction(char s[])
{
int n = 0;
int d = 1;
char *p1,*p2;
p1 = strtok(s,"/,");
p2 = strtok(NULL,"/,");
if (p1 != NULL)
{
n = atoi(p1);
}
if (p2 != NULL)
{
d = atoi(p2);
}
set(n, d);
}
void Fraction::normalize()
{
if (num == 0 || den == 0)
{

num = 0;
den = 1;
}
int n = lcd(num,den);
num /= n;
den /= n;
}
int Fraction::lcd(int a,int b)
{
if (b == 0)
{

return a;
}
else return lcd(b,a%b);
}

2个回答

qq423399099      2016.04.10 21:57

1.Fraction p3("12,14");不能这样，因为"12,14"是常量字符串，strtok企图修改常量区就会报异常，要改成栈区或者堆区的字符数组或者字符串
2.p1 = strtok(s,"/,");和p2 = strtok(NULL,"/,");楼主加一个/要干嘛？就算转义也应该是\,而且,是不用转义的

`````` #include <iostream>
using namespace std;
class Fraction
{

private:
int num, den;
public:
Fraction(char s[10]);
void set(int n, int d){ num = n; den = d;normalize(); }
int get_x(){ return num; }
int get_y(){ return den; }
private:
void normalize();
int lcd(int a,int b);
};
int main()
{
char str[10] = "12,14";
Fraction p3(str);
cout << p3.get_x() << endl;
cout << p3.get_y() << endl;
system("pause");
return 0;
}
Fraction::Fraction(char s[])
{
int n = 0;
int d = 1;
char *p1,*p2;
p1 = strtok(s,",");
p2 = strtok(NULL,",");
if (p1 != NULL)
{
n = atoi(p1);
}
if (p2 != NULL)
{
d = atoi(p2);
}
set(n, d);
}
void Fraction::normalize()
{
if (num == 0 || den == 0)
{

num = 0;
den = 1;
}
int n = lcd(num,den);
num /= n;
den /= n;
}
int Fraction::lcd(int a,int b)
{
if (b == 0)
{

return a;
}
else return lcd(b,a%b);
}
``````
caozhy      2016.04.10 21:50

Fraction p3("12,14");
->
char s[100]="12,14";
Fraction p3(s);

Gargan 谢谢！