-4

我想在同一行打印多个值,然后转到下一行并打印相同的值并转到下一行,依此类推。例如:-

3 5 10
2 7 15

在 C 语言中。

#include <stdio.h>

int main()
{
   int a,b,n,i,j,l;

   printf("Enter total digit in a line:");

   scanf("%d",&n);

   printf("Enter number of lines:");

   scanf("%d",&l);

   for(i=1;i<=l;i++)
   {
      for(j=1;j<=n;j++)
      {
         printf("enter values for line :");
         scanf("%d",&n);
      }
   }
}
4

2 回答 2

2

对于每一行,使用 eg 将输入读取为字符串fgets,然后strtok在循环中使用 eg 来提取每个数字并使用strtol将数字转换为整数值,然后将它们相加。


上述解决方案包含四个部分,因此让我们将其拆分并一次做一个。

  1. 对于每一行,使用 读取输入fgets

    这非常简单,因为您所要做的就是使用外部循环并要求用户在那里输入数字,并在那里读取输入:

    for (i = 1; i <= l; i++)
    {
        printf("Enter numbers for line number %d: ", i);
    
        char input[128];
        fgets(input, sizeof(input), stdin);
    }
    
  2. 在循环中使用strtok以从输入中提取每个数字。

    for (i = 1; i <= l; i++)
    {
        /* The code to read the input... */
    
        char *pointer = strtok(input, " ");
        while (pointer != NULL)
        {
            /* `pointer` is now pointing to the next space-delimited number */
    
            /* Find the next space-delimited number */
            pointer = strtok(NULL, " ");
        }
    }
    
  3. 用于strtol将数字转换为整数值。

    {
        /* `pointer` is now pointing to the next space-delimited number */
        /* Convert string to number */
        long value = strtol(pointer, NULL, 10);
    
        /* Find the next space-delimited number... */
    }
    
  4. 最后添加该行中的所有值。

    for (i = 1; i <= l; i++)
    {
        long sum = 0;
    
        /* ... */
    
        {
            long value = strtol(pointer, NULL, 10);
            sum += value;
        }
    
        printf("The sum of all values on line %d is %ld\n", i, sum);
    }
    

综上所述,我们得到以下代码:

for (i = 1; i <= l; i++)
{
    printf("Enter numbers for line number %d: ", i);

    char input[128];
    fgets(input, sizeof(input), stdin);

    long sum = 0;

    char *pointer = strtok(input, " ");
    while (pointer != NULL)
    {
        /* `pointer` is now pointing to the next space-delimited number */
        /* Convert string to number */
        long value = strtol(pointer, NULL, 10);
        sum += value;

        /* Find the next space-delimited number */
        pointer = strtok(NULL, " ");
    }

    printf("The sum of all values on line %d is %ld\n", i, sum);
}

注意:上面的代码没有错误检查。我把它作为练习留给读者。

于 2013-07-26T06:22:05.327 回答
0

例如

#include <stdio.h>

int main(void){
    int n, l, i, j;

    printf("Enter total digit in a line:");
    scanf("%d", &n);

    printf("Enter number of lines:");
    scanf("%d", &l);

    for(i=1;i<=l;i++){
        long sum =0;
        printf("enter values for line : ");
        for(j=1;j<=n;j++){
            int num;
            scanf("%d", &num);//n : Names are colliding
            sum += num;
        }
        printf("sum of line : %ld\n", sum);
    }
    return 0;
}
于 2013-07-26T08:28:29.107 回答