我的项目是打印0到100之间的素数,但也显示每行5个素数。
//Print first 100 Prime numbers.
for (i = 1; i <= 100; i++) {
int counter=0;
for(num =i; num>=1; num--) {
if(i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
//Display the output of 5 numbers per row.
System.out.print(" " + i);
if(i % 5 == 1) {
System.out.print("\n");
}
//Prime number is assigned to the empty string class variable.
displayPrimes = displayPrimes + i + " ";
}
}素数的输出效果很好,我只是很难让它们分配给每一行5个值。
当前的输出如下所示:
0-100素数是: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
这是用于调整每行5个值的代码。
//Display the output of 5 numbers per row.
System.out.print(" " + i);
if(i % 5 == 1) {
System.out.print("\n");
}发布于 2016-11-20 22:07:57
只需再添加一个int变量,就可以计算每一行打印了多少素数。当它在一行中打印5个数字时,会转到下一行,然后重置计数器(将变量设置为0)。如下所示:
int count =0;
for (i = 1; i <= 100; i++) {
int counter=0;
for( num =i; num>=1; num--)
{
if(i % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
//Display the output of 5 numbers per row.
System.out.print(" " + i);
count++;
if(count == 5) {
System.out.print("\n");
count = 0;
}
//Prime number is assigned to the empty string class variable.
displayPrimes = displayPrimes + i + " ";
}
}发布于 2016-11-20 22:09:41
您不能再次使用i,您需要使用一个新变量(我使用了currentPrime)。因为i是素数本身,而不是素数的索引。
另外,还需要在for循环中将i = 1添加到int i = 1,否则代码将不会编译。
int currentPrime = 1;
for (int i = 1; i <= 100; i++) {
int counter=0;
for(int num =i; num>=1; num--)
{
if(i % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
//Display the output of 5 numbers per row.
System.out.print(" " + i);
currentPrime++;
if(currentPrime % 5 == 1)
{
System.out.print("\n");
}
//Prime number is assigned to the empty string class variable.
displayPrimes = displayPrimes + i + " ";
}
}发布于 2016-11-20 22:13:24
通过检查
if (i % 5 == 1)您正在检查除以I后的余数是否为1。由于I是素数,这意味着每当素数大于5的倍数时,新行将打印出来(因此,在11、31、41等之后,它给了您一条新行)。
您需要做的是设置一个单独的计数器变量,以跟踪您在该行上打印了多少素数。您可以在每次打印新素数时增加此变量,然后打印新行,并在素数变量达到5时重新设置它。
https://stackoverflow.com/questions/40709877
复制相似问题