5

初心者のCの質問があります。以下のコードで欲しい...

include <stdio.h>

void iprint();
int i=0;

int main()
{
  int j;

  for (j=0; j<50; j++)
    {
      iprint(i);
      printf("%d\n",i);
    }
}

void iprint(i)
{
  i +=1;
  //printf("%d\n",i); 
}

...関数「iprint」が呼び出されるたびにiの値を更新します。たとえば、iを更新して、反復2の値1、反復2の値3などでメインで使用できるようにします。

コードを次のように変更することでこれを達成しました。

 include <stdio.h>

int iprint();
int i=0;

int main()
{
  int j;

  for (j=0; j<50; j++)
    {
      i= iprint(i);
      printf("%d\n",i);
    }
}

int iprint(i)
{
  i +=1;
  //printf("%d\n",i); 
  return(i);
}

それを実現するには return(i) する必要がありますか? 質問する理由は、i を使用する関数がたくさんある場合、それらの間で i を渡す必要があるのは少し面倒だからです。代わりに、matlab でグローバル変数を更新するように更新できれば、それは素晴らしいことです。出来ますか?

4

5 に答える 5

0

メイン関数自体で i の値を増やした可能性があります。ちなみに関数を

int iprint(int i){
/*you have to mention the type of arguemnt and yes you have to return i, since i  
variable in this function is local vaiable when you increment this i the value of  
global variable i does not change.
*/
return i+1;
}

声明

i=iprint(i); //this line updates the value of global i in main function


これは、変数のコピーが作成される「値渡し」メソッドによって関数に値を渡すため、このように発生します。iprint メソッドをインクリメントすると、グローバル変数 i のコピーがインクリメントされます。グローバル変数はそのまま残ります。

于 2013-09-23T10:31:03.597 に答える