我在使用命令提示符获取变量(在命令提示符中编写)并在程序中使用它们时遇到困难。我的想法是使用以下方法编译程序:
gcc main.c
并通过运行创建的 a.exe 和后面的参数来执行它。
如下:
C:\Users\Pc\Desktop\resistance>gcc main.c
C:\Users\Pc\Desktop\resistance>a.exe 0.0005 1.5 160
48.000000 49.000000 49.000000 提供的参数不足
最后一行是我从代码中收到的值,从我提供的参数来看,该值不正确。
以及代码由“未提供足够的参数”if 语句终止的事实。这又令人困惑,因为 *argv[] 从 0 *argv[0] 开始,它应该等于“a.exe”,因此后面的参数应该 = *argv[1]... 等
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
float areaOfcircle(float radius_circle)
{
float area_circle;
area_circle = M_PI * radius_circle * radius_circle;
return area_circle;
}
void resitance_current(float length, float area_circle, float voltage, float* resistance, float* current)
{
float resistivity;
resistivity = 1.782*pow(10, -8);
*resistance = ((resistivity*length) / area_circle);
*current = (voltage / *resistance);
}
int main(int argc, char *argv[])
{
float radius, voltage, length, current, resistance;
float length_u, length_l;
voltage = *argv[1];
length = *argv[2];
radius = *argv[3];
printf("%f %f %f", voltage, length, radius);
//char response, yes;
// take radius as input
//printf("Enter the radius of wire : ");
//scanf("%f", &radius);
if (argc != 3)
{
printf("Not enough arguments supplied");
}
else
{
if (radius < 0)
{
exit(1);
}
else
{
//printf("Enter the Voltage of circuit : ");
//scanf("%f", &voltage);
if (voltage < 0)
{
exit(1);
}
else
{
//printf("Enter the Length of Wire : ");
//scanf("%f", &length);
if (length < 0)
{
exit(1);
}
else
{
resitance_current(length, areaOfcircle(radius), voltage, &resistance, ¤t);
printf("Resistance = %f , Current = %f\n", resistance, current);
printf("\nEnter the Upper Length of Wire : ");
scanf("%f", &length_u);
printf("\nEnter the Lower Length of Wire : ");
scanf("%f", &length_l);
if ((length_l < 0) || (length_l >= length_u))
{
exit(1);
}
else
{
for(length_l = length_l; length_l<=length_u; length_l++)
{
length = (length_l + 1);
resitance_current(length, areaOfcircle(radius), voltage, &resistance, ¤t);
printf("\nLength = %0.3f Resistance = %0.3f , Current = %0.3f", length, resistance, current);
}
}
}
}
}
}
return 0;
}
在第 23-25 行,我尝试为提供的参数分配变量名称。以便更轻松地阅读代码。
我试图寻求帮助的主要问题是如何获取(从program.exe名称后面的命令行读取/输入的整数/ float 字并在代码中正确使用。
*代码是预先编写的,这是最后一步,因此如果我错过了代码中的任何内容,请也提供帮助,提前致谢。希望你能帮忙:)
最佳答案
警告程序的路径名是第一个参数,因此argc必须与您的情况下的4进行比较,这就是您有这种行为的原因
另一句话:您需要在之前检查argc才能访问argv
关于c - 通过命令提示符 C 语言提供浮点参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54171079/