我正在为作业编写输入部分,如果命令行输入是一个它应该接受键盘输入的部分 - 其中一个输入不起作用。
这是我遇到问题的代码段。如果行scanf(“%lf%lf”,& r1,& r2);单独留下它会给出一个分段错误 - 如果它被改为写入另一个变量那么一切正常。我很难理解为什么它是导致问题的变量,它从上面的行中字面上粘贴,我将四个字符从k更改为r并且两个变量在同一行中声明!请尽快帮助,除非我能解决这个问题,否则我无能为力。我已经尝试将变量名称更改为l1和l2,但是当功能失调线与功能线非常相似时,我想不出别的事情
double time[10000], x1[10000], x2[10000], v1[10000], v2[10000];
double m1, m2, k1, k2, r1, r2, w1, w2;
int count, inmethod;
time[0] = 0;
x1[0] = 0; x2[0] = 10;
v1[0] = 0; v2[0] = 0;
m1 = 5; m2 = 5;
k1 = 5; k2 = 5;
r1 = 5; r2 = 10;
w1 = 0; w2 = 0;
sscanf(argv[1], "%d", &inmethod);
// printf("%d \n", inmethod);
if((argc == 2) && ((inmethod == 1) || (inmethod == 0)))
{
}
else
{
printf("enter 1 for file input or 0 to enter input via the keyboard. you will be able to save your input for future use.\n");
return(EXIT_FAILURE);
}
if(inmethod == 1)
{
printf("system properties: \n");
printf("please enter m1 then m2, seperated by a space and followed by enter\n");
scanf("%lf %lf", &m1, &m2);
printf("please enter k1 then k2, seperated by a space and followed by enter \n");
scanf("%lf %lf", &k1, &k2);
printf("please enter r1 then r2, seperated by a space and followed by enter \n");
scanf("%lf %lf", &r1, &r2);
printf("please enter w1 then w2, seperated by a space and followed by enter \n");
scanf("%lf %lf", &w1, &w2);
printf("initial conditions: \n");
printf("please enter x1[0] then x2[0], seperated by a space and followed by enter \n");
scanf("%lf %lf", &x1[0], &x2[0]);
printf("please enter v1[0] then v2[0], seperated by a space and followed by enter \n");
scanf("%lf %lf", &v1[0], &v2[0]);
}
答案 0 :(得分:2)
你的代码看起来不错。它为我编译并且工作正常。
请检查您的输入值。 scanf对于输入验证来说真的很弱,你需要检查函数返回并做好准备。如果您需要接受这样的键盘输入,请尝试使用gnu readline或具有更好输入功能的库。