我在这里的代码只能得到87%的代码,因为“带有非正参数的加法参数什么也没做。我该如何解决呢?我尝试了更多的方法,但是我什至无法解决此错误在同学的帮助下
说明是:
对于此分配,您将创建一个存储分数的类。该类将包含两个整数值:分子和分母。对于您的班级,我们将坚持正分数,这意味着分子和分母都必须都大于0。
在以前的作业中,我们要求将您的班级命名为Main。在此分配中,必须将类命名为Fraction。
首先,下载模板文件Fraction.java(链接到外部站点。)。您的工作是将以下各节中描述的构造函数和方法添加到此模板文件中声明的Fraction类中。
分数应包括两个构造函数:
Fraction():创建分数1/1的默认构造函数
分数(整数n,整数d):如果n为正数,则将分子设置为n。否则,将分子设置为1。如果d为正,则将分母设置为d。否则,将分母设置为1。
分数应包括以下方法:
String toString():以字符串形式返回分数,形式为“分子/分母”。例如1/2或5/3。
String mixedNumber():返回任何不正确的(高优先级的)分数作为混合数字,例如2 3/5。如果小数部分的分子为0,则仅返回整数的整数部分。如果分数是正确的,则仅返回分数部分。
void add(int n,int d):如果n和d均为正,则将分数n / d添加到该分数。否则,请保持分数不变。通常,分数a / b和c / d之和为(ad + cb)/(b * d)。
要测试您的代码,请将运行程序类student_fraction_runner.java(链接到外部站点。)下载到保存Fraction.java的同一文件夹中。执行方法student_fraction_runner.main并验证输出是否与下面列出的样本运行匹配。
我们将使用类似但不同的跑步者为程序评分。为了通过所有测试,您将需要更改student_fraction_runner.java以测试不同的值,以确保您的程序符合要求。注意:您将不会提交student_fraction_runner.java。提供此文件是为了帮助您测试类Fraction的实现。
完成编码和测试后,将整个Fraction类复制并粘贴到Code Runner中,然后按“提交答案”,以使您的作业记为已交。我们将在以后的作业中返回并改进Fraction类(您可能已经发现了如何实现该类的潜在缺陷),因此请务必保存您的工作。
public class Fraction
{
private int numerator;
private int denominator;
// TODO write default constructor
public Fraction()
{
numerator = 1;
denominator = 1;
}
// TODO write constructor for fraction n/d where n, d > 0
public Fraction(int n, int d)
{
//Set num to n if pos, else 1
if (n > 0){
numerator = n;
}
else {
numerator = 1;
}
if (d > 0) {
denominator = d;
}
else {
denominator = 1;
}
}
// TODO write method to return fraction as a String
public String toString()
{
return numerator + "/" + denominator;
}
// TODO write method to return fraction as a mixed number String
public String mixedNumber()
{
if (numerator >= denominator) {
int frac = numerator / denominator;
int mod = numerator % denominator;
//Return integer of improper frac
if (mod == 0) {
return Integer.toString(frac);
}
else {
return frac + " " + mod + "/" + denominator;
}
}
else {
return numerator + "/" + denominator;
}
}
// TODO write method to add fraction n/d to this Fraction
public void add(int n, int d)
{
int a = numerator;
int b = denominator;
int c = n;
if (n >= 0 && d >= 0) {
numerator = (a*d + c*b);
denominator=(b*d);
}
}
}
最佳答案
这样重写add方法:
public void add(int n, int d)
{
if( n >0) {
int a = numerator;
if ( d > 0) {
int b = denominator;
if( n < 0)
a = 1;
if(d<0)
b = 1;
int c = n;
if (n >= 0 && d >= 0) {
numerator = (a*d + c*b);
denominator=(b*d);
}
}}
关于java - 胶粘剂作业1,分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59934422/