每行需要10个输出

时间:2017-02-05 19:27:03

标签: c if-statement for-loop

我在修改一些代码时遇到了麻烦。我的代码取一个数字“n”并计算出许多素数。我需要为每行输出数据显示10个素数。任何提示将不胜感激。

#include <stdio.h>

int main()
{
   int n, i = 3, count, c;

   printf("How many primes would you like?");
   scanf("%d",&n);

   if ( n >= 1 )
   {
      printf("2");
   }

   for ( count = 2 ; count <= n ;  )
   {
      for ( c = 2 ; c <= i - 1 ; c++ )
      {
         if ( i%c == 0 )
            break;
      }
      if ( c == i )
      {
         printf(" %d",i);
        count++;
      }

      i++;
   }

   return 0;
}

3 个答案:

答案 0 :(得分:1)

试试

printf(" %5d", i);
   /*     ^ to help align the numbers

if ((count + 1) % 10 == 0)
    fputc(stdout, '\n');

在您打印2时第一次修复。

答案 1 :(得分:1)

一种方法是使用另一个计数器变量,每次打印一个数字时都会递增。使用1

初始化它
int counter = 1;

如果条件\n(counter % 10 == 0),则按true打印新行:

if (counter % 10 == 0)
           printf("\n");

这是您的完整代码,每行打印10个数字:

#include<stdio.h>

int main()
{
   int n, i = 3, count, c;
   int counter = 1;            // <------ added this

   printf("How many primes would you like?");
   scanf("%d",&n);

   if ( n >= 1 )
   {
      printf("2");
   }

   for ( count = 2 ; count <= n ;  )
   {
      for ( c = 2 ; c <= i - 1 ; c++ )
      {
         if ( i%c == 0 )
            break;
      }

      if ( c == i )
      {
          if (counter % 10 == 0)     // <------ added this if-statement
                  printf("\n");

          printf(" %2d", i);
          counter++;              // <------ added this
          count++;
      }

      i++;
   }
   printf("\n");
   return 0;
}

答案 2 :(得分:-1)

bool is_prime(int anyNum)   //takes an integer array returns, is_prime
{
    bool is_prime = true;
for (int c = 2; c <= anyNum - 1; c++)
{
    if (anyNum % c == 0)
    {
        //printf("%d is not prime\r\n" , anyNum);
        is_prime = false;
    }
}
return is_prime;
} 

int main()
{
int num_primes;
printf("How many primes would you like: ");
std::cin >> num_primes;

printf("\r\nScanned Primes Are---\r\n");
int foundPrimes = 0;
int x = 0;
for (; x <= num_primes; x++)
{
    bool gotLuckyFindingPrime = is_prime( x );
    if (gotLuckyFindingPrime)
    {
        if (foundPrimes % 10 == 0)
        {
            printf("\r\n");
        }
        printf("     %d", x);
        foundPrimes = (foundPrimes + 1) % 10;
    }
}
}

也可以处理在cmd上显示的十位数字,您可以尝试格式化