【问题标题】:Multiplication Table For Loop循环乘法表
【发布时间】:2013-09-17 22:19:05
【问题描述】:

这是我写的代码;它进入一个无限循环,我不知道为什么..

import java.io.*;

public class Multi{
    public static void main(String args[])throws IOException{

    int num;
    BufferedReader inpt = new BufferedReader (new InputStreamReader (System.in));

    System.out.print("Enter a number: ");
    num=Integer.parseInt(inpt.readLine());

    int z,x,y;

    while (num>=1 || num<=11){
        for(z=1; z<=num; z++){
            for(x=1; x<=z; x++){

                y=z*x;

                System.out.print(y+" ");

            }
            System.out.println();
        }

    }

  }
}

我想在这个中展示的输出是,当一个人输入一个数字时,它会显示一个乘法表。

例如

Enter a number: 5

Result:

 - 1 2 3 4 5
 - 2 4 6 8 10
 - 3 6 9 12 15
 - 4 8 12 16 20
 - 5 10 15 20 25

Enter a number: 3

 - 1 2 3
 - 2 4 6
 - 3 6 9

【问题讨论】:

    标签: java loops infinite-loop


    【解决方案1】:

    您的while 条件永远不会为假:

    while (num>=1 || num<=11)
    

    每个可能的数字都是 >= 1

    另外,您需要将设置num 的代码放入while 循环中。

    【讨论】:

      【解决方案2】:
      //To get a multiplication table for the number get from user 
      
      
      #include<stdio.h>
      int main() {
              
          int i;
          int num;
          scanf("%d",&num);
      
          for(i=1; i<=10; i++){
              printf("%d\n",i*num);
          }
          
          
          return 0;
      }
      

      【讨论】:

      • 此代码只会产生 single 行输出。 OP 正在寻找一个 table 数字。
      • 是的,因为我们在其中添加了一个新行命令( \n )所以......它并不是一个真正的带有数字的表格,它的数学表格意味着一个数字与 1-10 内的数字相乘。 .
      猜你喜欢
      • 2020-10-22
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多