c - #在C中定义一个输入数字

标签 c c-preprocessor

我需要让用户在程序中输入一个数字,然后需要能够在程序中的许多其他部分功能中使用该数字。有办法做到吗?

这是代码:

#include <stdio.h>
#include <math.h>
#define W 8.
#define H 4.

double ellipse(double);

typedef double (*DfD) (double);

double simpsons_int (DfD, double, double, int);

int main()
{
    double len, w, h, volume;
    printf("Please enter a length, width and height (in meters) of the an elliptical storage tank \n");
    scanf("%lf %lf %lf", &len, &w, &h);

    double a = h/2.*-1., r;
    for (double depth=10; depth<=400; depth=depth+10)
    {
        r=a+(depth/100);
        volume = len*simpsons_int(ellipse, a, r, 10000);
        printf("depth is %.1f, volume is %f\n", depth, volume);
    }
}

double ellipse(double y)
{
    double x;
    double A=W/2.;
    double B=H/2.;
    x=2*sqrt((1-(y*y)/(B*B))*(A*A));

    return x;
}

double simpsons_int(DfD f, double y0, double y1, int n)
{
    double y, sum, dy = (y1 - y0)/n;
    sum = f(y1) + f(y0);
    for(y = y0; y <= y1-dy; y += dy)
        sum += 2.0 * f(y+dy) + 4.0 * f(y + dy/2);
    return sum * dy / 6.0;
}

但我需要 H 和 W 是用户输入的数字,而不是 8 和 4。

最佳答案

您可以将其作为函数的参数传递,也可以将其声明为全局变量。我宁愿使用第一个,具体取决于应用程序。

1) 作为参数传递。你的函数应该是:

double ellipse(double y, double W, double H )
{
    double x;
    double A=W/2.;
    double B=H/2.;
    x=2*sqrt((1-(y*y)/(B*B))*(A*A));

    return x;
}

然后在 main() 中声明并扫描 W 和 H

2) 只需在 main() 之前声明 W 和 H;

double W,H;
int main()
{
    double len, w, h, volume;
    printf("Please enter a length, width and height (in meters) of the an elliptical storage tank \n");
    scanf("%lf %lf %lf", &len, &w, &h);
    scanf("%lf %lf",&W,&H);

    double a = h/2.*-1., r;
    for (double depth=10; depth<=400; depth=depth+10)
    {
        r=a+(depth/100);
        volume = len*simpsons_int(ellipse, a, r, 10000);
        printf("depth is %.1f, volume is %f\n", depth, volume);
    }

}

关于c - #在C中定义一个输入数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22748115/

相关文章:

python - 降低暴力破解的时间复杂度——最大素因数

c - 在C中使用UDP进行服务器-客户端文件传输

c - 将数字四舍五入为 int 大小边界字节数的方法

c# - 在 FAKE MSBuild 任务中定义预处理器符号

c++ - 如何让 C++ 应用程序在不同的 MS office 版本之间切换?

使用 C 预处理器计算 8 位 CRC?

c - 如何将 C 代码转换为汇编的十六进制表示形式?

c - Aztec (DB) 条码生成器

c - 在 C 中使用默认参数的最简单方法

C++预处理器基于参数的条件扩展