/**
*
标题:有理数类
有理数就是可以表示为两个整数的比值的数字。一般情况下,我们用近似的小数表示。但有些时候,不允许出现误差,必须用两个整数来表示一个有理数。
这时,我们可以建立一个“有理数类”,下面的代码初步实现了这个目标。为了简明,它只提供了加法和乘法运算。
class Rational
{
private long ra;
private long rb;
private long gcd(long a, long b){
if(b==0) return a;
return gcd(b,a%b);
}
public Rational(long a, long b){
ra = a;
rb = b;
long k = gcd(ra,rb);
if(k>1){ //需要约分
ra /= k;
rb /= k;
}
}
// 加法
public Rational add(Rational x){
return ________________________________________; //填空位置
}
// 乘法
public Rational mul(Rational x){
return new Rational(ra*x.ra, rb*x.rb);
}
public String toString(){
if(rb==1) return "" + ra;
return ra + "/" + rb;
}
}
使用该类的示例:
Rational a = new Rational(1,3);
Rational b = new Rational(1,6);
Rational c = a.add(b);
System.out.println(a + "+" + b + "=" + c);
请分析代码逻辑,并推测划线处的代码,通过网页提交
注意:仅把缺少的代码作为答案,千万不要填写多余的代码、符号或说明文字!!
*/
package java2013yusaiB;
/**
* @author hanhexin
*
*/
public class YS5 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Rational a = new Rational(1,3);
Rational b = new Rational(1,6);
Rational c = a.add(b);
System.out.println(a + "+" + b + "=" + c);
}
}
class Rational {
private long ra;
private long rb;
private long gcd(long a, long b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
public Rational(long a, long b) {
ra = a;
rb = b;
long k = gcd(ra, rb);
if (k > 1) { // 需要约分
ra /= k;
rb /= k;
}
}
// 加法
public Rational add(Rational x) {
return new Rational((ra * x.rb + rb * x.ra), rb * x.rb); // 填空位置
}
// 乘法
public Rational mul(Rational x) {
return new Rational(ra * x.ra, rb * x.rb);
}
public String toString() {
if (rb == 1)
return "" + ra;
return ra + "/" + rb;
}
}
答案:new Rational((ra * x.rb + rb * x.ra), rb * x.rb)
/**
*
标题:三部排序
一般的排序有许多经典算法,如快速排序、希尔排序等。
但实际应用时,经常会或多或少有一些特殊的要求。我们没必要套用那些经典算法,可以根据实际情况建立更好的解法。
比如,对一个整型数组中的数字进行分类排序:
使得负数都靠左端,正数都靠右端,0在中部。注意问题的特点是:负数区域和正数区域内并不要求有序。可以利用这个特点通过1次线性扫描就结束战斗!!
以下的程序实现了该目标。
static void sort(int[] x)
{
int p = 0;
int left = 0;
int right = x.length-1;
while(p<=right){
if(x[p]<0){
int t = x[left];
x[left] = x[p];
x[p] = t;
left++;
p++;
}
else if(x[p]>0){
int t = x[right];
x[right] = x[p];
x[p] = t;
right--;
}
else{
_________________________; //代码填空位置
}
}
}
如果给定数组:
25,18,-2,0,16,-5,33,21,0,19,-16,25,-3,0
则排序后为:
-3,-2,-16,-5,0,0,0,21,19,33,25,16,18,25
请分析代码逻辑,并推测划线处的代码,通过网页提交
注意:仅把缺少的代码作为答案,千万不要填写多余的代码、符号或说明文字!!
*/
package java2013yusaiB;
/**
* @author hanhexin
*
*/
public class YS6 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 25, 18, -2, 0, 16, -5, 33, 21, 0, 19, -16, 25, -3, 0 };
sort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
static void sort(int[] x) {
int p = 0;
int left = 0;
int right = x.length - 1;
while (p <= right) {
if (x[p] < 0) {
int t = x[left];
x[left] = x[p];
x[p] = t;
left++;
p++;
} else if (x[p] > 0) {
int t = x[right];
x[right] = x[p];
x[p] = t;
right--;
} else {
p++; // 代码填空位置
}
}
}
}
答案:p++