英文:
How can I get this values from a loop function?
问题
The output should be:
1 2 4 8 16
2 6 18 54 162
3 12 48 192 768
4 20 100 500 2500
5 30 180 1080 6480
6 42 294 2058 14406
英文:
The output should be:
1 2 4 8 16
2 6 18 54 162
3 12 48 192 768
4 20 100 500 2500
5 30 180 1080 6480
6 42 294 2058 14406
I am currently stuck with my code:
using System;
class Program
{
static void Main(string[] args)
{
int size = 6;
for (int i = 1; i <= size; i++)
{
int num = i;
if(num == 1) {
for (int j = 1; j < size; j++)
{
Console.Write(num + " ");
num *= 2;
}
Console.WriteLine();
}else{
int num2 = 2;
for (int j = 1; j < size; j++)
{
Console.Write(num2 + " ");
num2 *= 3;
}
Console.WriteLine();
}
}
}
}
答案1
得分: 2
基于代码和预期结果,公式应该类似于num *= i+1
,所以你可以尝试只使用内部循环而没有任何if
:
int size = 6;
for (int i = 1; i <= size; i++)
{
int num = i;
for (int j = 1; j < size; j++)
{
Console.Write(num + " ");
num *= i + 1;
}
Console.WriteLine();
}
英文:
Based on the code and the expected results formula should be something like num *= i+1
, so you can try just inner loop without any if
:
int size = 6;
for (int i = 1; i <= size; i++)
{
int num = i;
for (int j = 1; j < size; j++)
{
Console.Write(num + " ");
num *= i + 1;
}
Console.WriteLine();
}
答案2
得分: 1
这个也可以,使用 Math.Pow
。
int size = 6;
for (int i = 1; i <= size; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write(i * Math.Pow(i + 1, j));
Console.Write(" ");
}
Console.WriteLine();
}
英文:
This one would work too, using Math.Pow
int size = 6;
for (int i = 1; i <= size; i++)
{
for (int j = 0; j < 5; j++)
{
Console.Write(i * Math.Pow(i + 1, j));
Console.Write(" ");
}
Console.WriteLine();
}
答案3
得分: 0
将for
循环修改为以下形式:
for (int i = 1; i <= size; i++)
{
int num = i;
if (num == 1) {
for (int j = 1; j < size; j++)
{
Console.Write(num + " ");
num *= 2;
}
Console.WriteLine();
} else {
int num2 = i;
for (int j = 1; j < size; j++)
{
Console.Write(num2 + " ");
num2 *= i + 1;
}
Console.WriteLine();
}
}
英文:
Change the for
loop into this:
for (int i = 1; i <= size; i++)
{
int num = i;
if(num == 1) {
for (int j = 1; j < size; j++)
{
Console.Write(num + " ");
num *= 2;
}
Console.WriteLine();
}else{
int num2 = i;
for (int j = 1; j < size; j++)
{
Console.Write(num2 + " ");
num2 *= i+1;
}
Console.WriteLine();
}
}
答案4
得分: 0
尝试这个。
英文:
Try this one.
public static void Main(string[] args)
{
int size = 6;
for (int i = 1; i <= size; i++)
{
int num = i;
if(num == 1) {
Console.WriteLine();
for (int j = 1; j < size; j++)
{
Console.Write(num + " ");
num *= 2;
}
Console.WriteLine();
}else{
int num2 = i;
for (int j = 1; j < size; j++)
{
Console.Write(num2 + " ");
num2 *= i+1;
}
Console.WriteLine();
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论