1

分子の換算質量を計算するプログラムがあり、それを if 関数で呼び出したいと考えています。これは私が現時点で持っているコードです:

int program ();
int main()
{
    printf("Press 1 to calculate the reduced mass of a molecule or press any other button to exit:");
    scanf ("%lg",&repeat);

    if(repeat==1)
    {
    program();
    }
    else
    {
    return(0);
    }
}

int program ()
//etc...

私はCの経験があまりないので、説明が役立つかもしれません。また、これにより、関数を好きなだけ繰り返すことができるようになりますか?

4

2 に答える 2

1

C で開始する場合は、プログラム (コンパイル済みの C) 引数を使用して開始できます。このようにして、関数が呼び出される回数Nをプログラムに提供できます。program()

例えば

   // Includes that have some library functions declarations
   #include <stdio.h>
   #include <stdlib.h>

   // argc and argc can be provided to the main function.
   // argv is an array of pointers to the arguments strings (starting from 0)
   int main(int argc, char *argv[]) {
      if (argc < 2) return 1; // argc number of parameters including the program name itself
      int repeat = atoi(argv[1]); // atoi convert a string to integer

      // repeat-- decrements repeat after its value was tested against 0 in the while
      while (repeat-- > 0) {
         program();
      }

      return 0;
   } 

argcは 2 に対してテストされます。プログラム名自体が 1 番目の引数であるため、少なくとも 2 が必要です。

   ./myprog 5

program()を5 回実行します。

于 2013-01-14T13:22:25.050 に答える
0

I'm not too experienced with C, so an explanation might be useful.
正確に何を説明する必要があるのか​​わからない:

int program (); <-- function prototype for "program" defined here so you can call it in
int main()      <--  main. 
{
    // Display a message
    printf("Press 1 to calculate the reduced mass of a molecule or press any other button to exit:");
    // store the value typed by the user as a double, also it will accept scientific 
    // notation (that’s he g part). So you could enter 3.964e+2 if you wanted... an 
    // int or even a char would have been fine here
    scanf ("%lg",&repeat);

Also would this make it so that you can repeat the function as many times as you like? いいえ、そうではありません。まず、「リピート」の定義がないため、コンパイルされません。第二に、ループメカニズムがありません。for、、、再帰...多分それが何であれwhiledo/whileコードは、無限ループで非常に簡単に完了することができます。

int main()
{
    double repeat = 0;
    for(;;) {
        printf("Press 1 to calculate the reduced mass of a molecule or press any other button to exit:");
        scanf ("%lg",&repeat);

        if(repeat==1)
        {
            program();
        }
        else
        {
            return(0);
        }
    }
}
于 2013-01-14T16:22:31.880 に答える