【发布时间】:2014-03-13 01:08:05
【问题描述】:
例如,我有这段代码可以在不使用 * 符号的情况下将 2 个数字相乘,但是如何使用负数实现相同的效果?
public static void main(String[] args) {
// TODO code application logic here
Scanner in = new Scanner(System.in);
int result = 0;
System.out.println("Enter the first number: ");
int num1 = in.nextInt();
System.out.println("Enter the second number: ");
int num2 = in.nextInt();
if(num1==0 || num2==0) {
System.out.println("the profuct of these numbers is: 0");
}
for(int i =0; i <num1; i++)
{
result += num2;
}
System.out.println("the profuct od these numbers is: "+result);
}
}
【问题讨论】:
-
提示:如果X小于0,则将其视为
X = -1 * abs(X);。 -
提示:两个负数相乘得到一个正数。
-
提示:您的代码可以在 for 循环中的 num1 前面添加额外的减号并在末尾添加结果。
-
你为什么要那样做?键盘坏了? ;)
标签: java multiplication negative-number