【发布时间】:2019-06-07 19:48:31
【问题描述】:
我在使用命令提示符获取变量(在命令提示符中编写)并在程序中使用它们时遇到了困难。这个想法是我使用以下方法编译程序:
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]... ect
我的代码:
#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 名称后面的命令行读取/输入并在代码中正确使用的整数/浮点数。
*代码是预先编写的,这是最后一步,所以如果我错过了代码中的任何内容,请帮忙解决,提前致谢。希望你能帮忙:)
【问题讨论】:
-
您是否期望电压为 0.0005 (V?)、长度为 1.5 (m?)、半径为 160 (m??)?
-
是的,我是。鲍勃_
-
难道不是相反(160 V 和 0.0005m 的半径或 1.5 V 和 160m 的长度)?也许我想太多或使用了错误的单位,但是,这似乎并不是真正的 wire...
-
OT: about:
gcc main.c这是编译/链接程序的糟糕方式。建议:gcc -c -Wall -Wextra -Wconversion -pedantic -std=gnu11 main.c -o main.o,当它编译没有错误或警告时,然后gcc main.o -o main -
OT: about:
printf("Not enough arguments supplied");这告诉用户(几乎)除了他们犯了错误之外什么都没有。更好用:fprintf( stderr, "USAGE: %s voltage length radius\n", argv[0] );,因为它输出到stderr(应该这样)并告诉用户命令行上应该有什么,
标签: c command-line-arguments command-prompt