我正在编写一个程序,让用户输入一个分母和一个分母,程序然后将其转换为混合形式(9/8 - > 1 1/8等等)。除了分母大于提名者之外,它的工作正常。当我开始调试代码时,我发现了一些我无法理解的东西。下面是方法分数,在它结束时调用方法gcd(最大公共分频器)来确定将整数除法的余数和分母分开的内容。
public static int[] fraction(int nominator, int denominator) //Rewrites a fraction to mixed form
{
//nominator == 7 and denominator == 8
int[] result = {0, 0, 0};
int quotient;
int remainder;
if (denominator == 0)
return null;
if (nominator == 0)
{
result[0] = 0;
result[1] = 0;
result[2] = 0;
return result;
}
kvot = nominator/denominator;
rest = nominator % denominator;
result[0] = quotient;
result[1] = remainder/(gcd(remainder, denominator)); //According to the debugger, the values are still 7 and 8 here
result[2] = denominator/(gcd(remainder, denominator));
return result;
}
当使用上述值调用时,似乎出现了问题,因为第二种方法从第一种方法中获取的值是错误的。而不是7和8,它接收7和1.是否提供了代码中的错误,或者它似乎是在其他地方?
public static int gcd(int a, int b) //Calculates the greatest common divider for two integers
{ //The debugger tells me that a == 7 and b == 1, even though the method was called with 7 and 8
int temp, c;
if (b == 0)
{
System.out.println("Nominator is 0, error");;
}
if (b > a)
{
temp = b;
b = a;
a = temp;
}
c = a % b;
a = b;
b = c;
return a;
}
答案 0 :(得分:1)
您的gcd功能不正常。如果您使用欧几里德算法,您可以像这样计算gcd
var pieGenerator = d3.pie()
.value(function(d) {return d.quantity;})
.sort(function(a, b) {
return a.name.localeCompare(b.name);
});
var fruits = [
{name: 'Apples', quantity: 20},
{name: 'Bananas', quantity: 40},
{name: 'Cherries', quantity: 50},
{name: 'Damsons', quantity: 10},
{name: 'Elderberries', quantity: 30},
];
var fruits2 = [
{name: 'Blueberries', quantity: 40},
{name: 'Bananas', quantity: 40},
{name: 'Cherries', quantity: 50},
{name: 'Damsons', quantity: 10},
{name: 'Elderberries', quantity: 30},
];
var arcGenerator = d3.arc()
.innerRadius(75)
.outerRadius(200)
.padAngle(.02)
.padRadius(100)
.cornerRadius(4);
function doUpdate() {
update(fruits2);
}
function update(myData) {
var arcData = pieGenerator(myData);
var colorDomain = myData.map(function(a) {return a.name;});
var colorScale = d3.scaleOrdinal()
.domain(colorDomain)
.range(['#ff2800','#58595B','#006c93','#8D2048','#00746F'])
// Create a path element and set its d attribute
var u = d3.select('g')
.selectAll('path')
.data(arcData);
u.enter()
.append('path')
.attr('d', arcGenerator)
.each(function(d){
d3.select(this)
.style('fill',function(d) {
return colorScale(d.data.name);
})
});
u.exit().remove();
你也可以使用其他一些解决方案,但建议不行。