【问题标题】:What will be the result of next function and array in main? [closed]main 中下一个函数和数组的结果是什么? [关闭]
【发布时间】:2017-06-28 18:40:52
【问题描述】:

今天我尝试做一些新的事情,但我没有做对。谁能做到这一点并解释为什么会这样?提前谢谢你

#include<stdio.h>

void function(int a[],int n)/*The definition of function with void type,with parameters
int a[],int n */
{
  int i;// declared count,type integer//

  for(i=0;i<n;i++)//count goes from 0,to <n,and increment all time while goes//
      printf("%d",a[i++]);// printing on the screen integers (a[i],i=i+1)//
  printf("\n");// printing the newline //
}

main()
{
  int a[]={1,2,3,4,5,6,7}; // declaration of array with 7 elements //
  int n=5;// declaration of variable n type integer value of 5 //

  function(a,n) // calling the function with parametres a,n//
} // end of sequence //

在我的情况下,我得到了 1,2,3,4 的结果,因为我认为计数从 1 变为小于 n=5 的一个数,但是 IDE显示 135 的结果,我认为我的问题在于计数器...但欢迎所有建议,谢谢

【问题讨论】:

  • 你在循环中增加了两次i
  • 你将 i 增加了两次
  • @Jean-FrançoisFabre 这对我来说太愚蠢了,我错过了,现在我看到了一个无用的问题,谢谢
  • 注意:不要在您的 cmets 中陈述显而易见的内容。这样的 cmets 不会使您的代码更具可读性,而只会增加无意义的噪音。写下你的意图!如果您必须注释每一行,那么您的代码就是错误的。
  • main() 是一个无效的签名,甚至不是标准的。不允许使用隐式 int

标签: c arrays function


【解决方案1】:

请确保您发布格式正确的有效 C 代码。

注意,你得到的不是一百三十五,而是一、三、五。你得到它是因为你将循环计数器增加了两次。 这是一个工作的、更易读的版本:

#include <stdio.h>

void function(int a[],int n)
{
    int i;
    for(i = 0; i < n; i++)
        printf("%d ",a[i]);
    printf("\n");
}

int main(void)
{
    int a[]={1,2,3,4,5,6,7};
    int n=5;
    function(a,n); 

    return 0;
}  

【讨论】:

  • 也许 OP 还希望在每个数字后换行。因此,for 循环中的大括号将包含两个 printf() 函数或将其混合为单个 printf("%d \n",a[i]);会更好看。
  • 非常感谢,我也遇到了换行问题,我坚持认为该功能将在屏幕上打印每个换行的数字,但现在我看到它会被混合到一个 printf 中
  • 不客气。您可以在一个语句中执行此操作,也可以像 for(i = 0; i
  • @Vlad Diev 这么猜 :)
【解决方案2】:

替换

printf("%d",a[i++]);// printing on the screen integers (a[i],i=i+1)//

printf("%d",a[i]);// printing on the screen integers (a[i],i=i+1)//

在您的代码中,您将 i 递增了两次。偶尔一次,一次在 a[i++]

【讨论】:

  • 我以为计数器只会增加一个……谢谢
猜你喜欢
  • 2022-06-16
  • 1970-01-01
  • 2021-11-20
  • 2016-09-12
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多