我有一个计算器可以减少分子的质量,并希望用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不太熟悉,所以解释可能有用。这也是为了让你可以多次重复这个功能吗?
答案 0 :(得分:1)
如果从C开始,可以先使用程序(已编译的C)参数。通过这种方式,您可以为程序提供 N 多次调用program()
函数。
E.g。
// 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个,使用N. E.g。
./myprog 5
将运行 program() 5次。
答案 1 :(得分: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);
}
}
}