如何对预定义数组求平方并在3个整数空间中打印 [英] How do I square a predefined array and print it in 3 integer spaces

查看:49
本文介绍了如何对预定义数组求平方并在3个整数空间中打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要对预定义数组求平方,但问题是迭代取决于用户输入的数字.我只是Java的新手,也不知道它是如何工作的.

I need to square the predefined array, but the problem is the iteration depends on what number the user enter is. I'm only new to java and do not know how it works.

int[] array = {1, 2, 3, 4, 5}; // Predefined array.

Scanner in = new Scanner(System.in);

int num = in.nextInt(); // Number of loop.
int sq = 0, sq2 = 0, sq3 = 0, sq4 = 0, sq5 = 0;

for (int i = 0; i < num; i++) {
    sq = array[i] * array[i];
    sq2 = array[i] * array[i];
    sq3 = array[i] * array[i];
    sq4 = array[i] * array[i];
    sq5 = array[i] * array[i];
}

for (int i = 0; i < num; i++) {
    System.out.println(sq);
    System.out.println(sq2);
    System.out.println(sq3);
    System.out.println(sq4);
    System.out.println(sq5);
}

输入:

1 //iteration

输出:

1
1
1
1
1

预期输出:

001
004
009
016
025

推荐答案

i 的值开头是0.因此,所有值实际上都存储第0个元素的平方,该第0个元素是数组中的第一个元素,这意味着它们都存储了"1"的平方.您的代码应如下所示:

The value of i is 0 in the beginning. So all the values are actually storing the square of the 0th element that is the first element in the array which means they are all storing the square of "1". Your code should be somewhat like this:

int[] array = {1, 2, 3, 4, 5}; // Predefined array.
    
Scanner in = new Scanner(System.in);
      
int num = in.nextInt(); // Number of loop.
int[] sq = {0, 0, 0, 0, 0};
  
for(int i = 0; i < num; i++)
{
    for(int j = 0; j < 5; j++)
    {
        sq[j] = array[j] * array[j];
    }
}

for(int i = 0; i < 5; i++)
{
  System.out.println(sq[i]);
}

这应该可以完成工作.

这篇关于如何对预定义数组求平方并在3个整数空间中打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆