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)参数开始。这样,您可以向程序提供Nprogram()次要调用该函数的次数。

例如

   // 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 进行测试,因为程序名称本身是第一个参数,所以您至少需要 2,使用 NEg

   ./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, while, do/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 回答