输入整数输出浮点数,反之亦然

时间:2017-11-19 23:02:44

标签: java

我想创建一个程序来使用重载的概念执行乘法的算术运算。所以,如果它得到2整数,它将输出一个浮点数。如果我输入2浮点数,它必须输出整数。我怎么能创建这样的程序,因为我是编程新手。感谢

3 个答案:

答案 0 :(得分:1)

制作类似于此的方法:

***int* multiply**(float x, float y){

return (*int*)(x*y)

}

***float* mulitply**(int x, int y){

return (*float*)(x*y)

}

返回变量算术但是编译器想要弄清楚然后转换/返回?

函数重载是使用具有相同名称和不同参数的方法(或者您想要调用它们的参数)的过程。

这两个函数都是这样的:

float math(int, int)
int math(float,float)

非常相似吗?这是好处。

在main方法中或使用这些方法的任何地方,如果传递给它们的变量(int x,int y)或(float x,float y)未确定[即由用户输入并且它们可能输入整数或因此,浮点数变量未确定为int或者浮点数。]如果我们想要使用方法将它们相乘,这将是很重要的。

我们的方法是否需要采用int或float类型的参数?

使用函数重载,我们可以调用方法math(一些var1,一些var2),让计算机根据值决定使用int math(float,float)或float math(int,int)的方法。如果值为4和5,则方法为math int,int,如果值为5.4 35.6,则value方法为int math(float,float)

还记得在返回浮点值但将其转换为int时会有一些不准确之处。这有两个方面,谢谢@ Dawood ibn Kareem

答案 1 :(得分:-1)

你应该看一下单一责任原则,它说明你应该把它分成两类,甚至完全性的依赖性倒置原则。您还应该考虑是否要将double的舍入或向下舍入为int。

class Calc {

  public static void main(String[] args) {
    System.out.println(Calc.multiply(4, 5));
    System.out.println(Calc.multiply(2.3, 6.7));
  }

  private static double multiply(int a, int b) {
    int x = a * b;
    return (double)x;
  }

  private static int multiply(double a, double b) {
    double x = a * b;
    return (int)x;
  }

}

答案 2 :(得分:-2)

class First
{
void Multiplication(int a,int b)
{
int c=a*b //here I don't need to convert because .0 comes on it!
System.out.println(c);
}
void Multiplication(float a,float b)
{
float c=Math.round(a*b);// which rounds the float point to 0
System.out.print(c);// 
}
}
class Multi
{
public static void main(String[] args)throws IOException
{
First Edu=new First();
float a=Float.parseFloat(JOptionPane.showInputDialog("Enter The First Number"));
float b=Float.parseFloat(JOptionPane.showInputDialog("Enter The Second Number"));
Edu.Multiplication(a,b);
}}