简体   繁体   English

我不明白为什么这个工作

[英]I don't understand why this working

public static void main(String args[]){

    Scanner s = new Scanner(System.in);
    int x;
    int y;
    int z = 0;
    x = s.nextInt();
    y = s.nextInt();

    while(y != 0){
        z += x;
        y--;
    }
    System.out.println(z);
}

This is all. 这就是全部。 This code calculates x*y but doesn't use *. 此代码计算x * y,但不使用*。 It was just a (task ?) somebody told me. 那只是一个(任务?)有人告诉我。 And my question is why this is working with negative numbers. 我的问题是,为什么这要使用负数。 That x can be negative is obvious but why can y be. x可以为负是显而易见的,但是y为什么可以为负。

Edit: I wrote this code on my own so I know why it works without *. 编辑:我自己编写了此代码,所以我知道为什么不带*的原因。 That's not the question. 那不是问题。 I can input 5 for x and -5 for y and i get -25. 我可以为x输入5,为y输入-5,我得到-25。 But why? 但为什么? Everytime he adds one more time x to zy goes 1 down. 每次他再增加zy的时间x就会下降1。 But after the 5th time it stops. 但是在第5次之后它停止了。

If you put the "z" print inside the while you will understand. 如果您将“ z”打印内容放到里面,您将会了解。

This code makes overflow. 此代码使溢出。 Reach the maximum value that the int permit and decrease again from there 达到int允许的最大值并从那里再次减小

This code makes multiple sums. 此代码产生多个和。 So it can sum the number 2, 3 times, and thats how it does 2*3. 因此,它可以将数字2相加3次,这就是2 * 3的方式。

The y can be negative because the if is seeing != than 0, not < than 0. y可以为负,因为if看到!=大于0,不小于0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM