我是编程新手,我正在尝试计算n阶乘,我不知道这是否有效,但目前我收到一个错误,说"n"未声明。正在处理函数。我真的很感激你能给我关于他的程序的任何提示
#include <math.h>
#include <stdio.h>
#define PI 3.14159
#define e 2.72
void printDirections (void);
double readValue (void);
double calcNFact (double n);
void printN (void);
int main (void)
{
double n, n_fact;
double eq1, eq2, eq3, eq4;
printf ("This program Calculates n factorial. n");
// print directions
printf ("Enter the value of n and the programn will calculate n!");
// read the value of n from the user
printf ("Enter n: /n");
n = readValue ();
// Calculate n factorial
n_fact = eq1 * eq2 * eq3 *eq4;
// print the results
printN (n);
return 0;
}
// Prints the directions
void printDirections (void)
{
printf ("Enter the value of n and the programn will calculate n!");
return ;
}
// Read the value of n from the user
double readValue (void)
{
double value;
printf ("Enter n: /n");
scanf ("%lf", &value);
return (value);
}
// Calculate and return n factorial, pass in n
double calcNFact (double n)
{
double n_fact, eq1, eq2, eq3, eq4;
eq1 = ((2 * n) + (1 / 3)) * PI;
eq2 = sqrt (eq1);
eq3 = pow (e, -n);
eq4 = pow (n, n);
n_fact = eq1 * eq2 * eq3 * eq4;
return n_fact;
}
//print n and n factorial
void printN (void)
{
printf ("n n: %.1f n", n);
printf ("n n!: %.2f n", n_fact);
return;
}
n
在printN
函数(以及n_fact
)内未声明。printN
应接受它们作为参数:
void printN (double n, double n_fact) {...}
所以你称之为:
printN(n, n_fact);
您的printN
函数无法读取变量n
和n_fact
,因为它们超出了范围。
C++中的可变作用域
此外,函数定义void printN (void)
中的参数签名与函数调用printN (n)
不一致。
您的变量n
/n_fact
不在函数printN
的范围内,这就是为什么它说"未声明"。
一种解决方案是将n
/n_fact
的值传递给函数printN
。