/*
功能:
根据输入的分子与分母,输出计算结果。无限非循环小数,直接输出计算结果
输入:
denominator 分母
numerator 分子
输出:
decimaltostring 输出计算结果
返回:
-1 失败
0 成功
*/
int Calculate(const int numerator, const int denominator ,char *decimaltostring)
{
if (denominator == 0 || decimaltostring == NULL) {
return -1;
}
std::set<int> remainder;//余数
int decimal[100]; //小数
int b = numerator / denominator;
int size = 0;
while (b) {
size++;
b /= 10;
}
b = numerator / denominator;
while (size > 1) {
*decimaltostring = b / ((size - 1) * 10) + '0';
b %= (size - 1) * 10;
decimaltostring++;
size--;
}
*decimaltostring = b + '0';
decimaltostring++;
int a = numerator % denominator; //余数
if (a == 0) {
*(++decimaltostring) = '\0';
return 0;
}
*decimaltostring = '.';
decimaltostring++;
remainder.insert(a);
int i = 0;
int flag = 0; //是否循环
while (i < 97) {
a *= 10;
int b = a / denominator;
decimal[i] = b; //保存结果
i++;
a %= denominator;
if (remainder.find(a) != remainder.end() && flag == 0) {
flag = i;
}
remainder.insert(a);
}
int flag2 = 0;
if (flag < 95 && flag > 0) { //发现为循环并且小数个数小于99 0.(***)\0 占用了5位 100-5=95
for (int k = 0; k < flag; k++) {
if (decimal[flag] == decimal[k] && flag2 ==0) {
*decimaltostring = '(';
decimaltostring++;
flag2 = 1;
}
*decimaltostring = decimal[k] + '0';
decimaltostring++;
}
*decimaltostring = ')';
}
else {
for (int k = 0; k < i; k++) {
*decimaltostring = decimal[k] + '0';
decimaltostring++;
}
}
*(++decimaltostring) = '\0';
return 0;
}
判断是否是循环小数的依据是每次做完除法后的余数前面是否出现过。比如:
1/7=0……1
10/7 =1……3
30/7 =4……2
……
50/7=7……1
我使用一个set去保存每次的余数。flag2是判断是否添加了'('
部分测试用例
int numerator = 11;
int denominator = 15;
char szResult2[100] = "0.7(3)";*/
/*int numerator = 1100;
int denominator = 15;
char szResult2[100] = "73.(3)";*/
/*int numerator = 100;
int denominator = 7;
char szResult2[100] = "14.(285714)";*/
int numerator = 14;
int denominator = 7;
char szResult2[100] = "2";
/*int numerator = 0;
int denominator = 7;
char szResult2[100] = "0"