gpt4 book ai didi

c - 使用 scanf 读取 double 的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 08:48:26 25 4
gpt4 key购买 nike

我正在为作业编写输入部分,如果命令行输入是它应该采用键盘输入的输入 - 这些输入之一不起作用。

这是我遇到问题的代码段。如果行 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]);

}

最佳答案

您的代码看起来不错。它为我编译并且工作正常。

请检查您的输入值。 scanf 对于输入验证来说真的很弱,你需要检查函数返回并为更糟的情况做好准备。如果您需要接受这样的键盘输入,请尝试使用 gnu readline 或具有更好输入功能的库。

关于c - 使用 scanf 读取 double 的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20657894/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com