如何在 C 中使用 scanf() 读取负双精度数?
我正在学习 C 的基础知识并编写一个简单的一阶方程求解器。我希望输入正好是 ax+b=c 或 ax-b=c,其中 a、b、c 是 double 类型。我正在使用 scanf() 读取用户输入并检查其形式是否正确。但是,如果我输入负双精度数,例如 -4.6,作为等式中的“a”,scanf()
将无法正确读取 a、b、c。我在 scanf()
中使用 %lf。那么我如何读取负双精度呢?非常感谢。
我的代码:
#include <stdio.h>
int main(void)
{
double a,b,c,x;
printf("Enter the expression:\n");
if (scanf("%lfx%lf=%lf", &a, &b, &c) == 3)
{
x = (c - b)/a;
printf("x=%.2f\n", x);
}
else if (scanf("%lfx+%lf=%lf", &a, &b, &c) == 3)
{
x = (c - b)/a;
printf("x=%.2f\n", x);
}
else
printf("Invalid expression\n");
return 0;
}
I'm learning basics of C and writing a simple first order equation solver. I want the input to be exactly ax+b=c or ax-b=c, where a, b, c are double type. I'm employing scanf() to read in user input and to check if it's of the correct form. However, if I enter a negative double, -4.6 say, as the "a" in the equation, scanf()
won't read the a,b,c correctly. I'm using %lf inside scanf()
. How do I read a negative double, then? Many thanks.
My code:
#include <stdio.h>
int main(void)
{
double a,b,c,x;
printf("Enter the expression:\n");
if (scanf("%lfx%lf=%lf", &a, &b, &c) == 3)
{
x = (c - b)/a;
printf("x=%.2f\n", x);
}
else if (scanf("%lfx+%lf=%lf", &a, &b, &c) == 3)
{
x = (c - b)/a;
printf("x=%.2f\n", x);
}
else
printf("Invalid expression\n");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
直接使用
scanf()
(而不是fgets()
和sscanf()
)的困难之一是找出它在哪里当它出错的时候。您还可以通过注意
scanf()
返回成功转换的数量来帮助自己。您应该进行测试:只要数据正确并且没有遇到 EOF,您所拥有的就应该可以正常工作。也就是说,调用是格式良好的;它发生的背景可能不那么清晰。
另外,由于您希望在两个术语之间允许使用“+”或“-”,因此您确实需要转向读取下一个标记(可能是负数、“x”、“+”或'-',和另一个(可能是负数)数字)。然后你可以解释这些。如果用户输入“-2.3x-4.5=9.1”,则使用
scanf()
是一场灾难,那么当扫描在(第二个)“-”上失败时,您将无法返回并以负数格式重新读取整个数据。或者您需要将分隔符“+”或“-”读入字符值。One of the difficulties with using
scanf()
directly (instead of, say,fgets()
andsscanf()
) is working out where it got to when it went wrong.You could also help yourself by noting that
scanf()
returns the number of successful conversions. You should be testing:What you've got should work OK as long as the data is correct and you don't encounter EOF. That is, the call is well formed; the context in which it occurs may not so clean.
Also, since you want to allow either '+' or '-' between the two terms, you really need to move towards a tokenizing mechanism that reads the next token (a possibly negative number, an 'x', a '+' or '-', and another (possibly negative) number). You can then interpret these. Using
scanf()
is a disaster if the user entered '-2.3x-4.5=9.1', then when the scan fails on on the (second) '-', you have no way to go back and reread the whole data with the negative format. Or you need to read the separator symbol '+' or '-' into a char value.