我尝试使用C中的scanf()读取2个值,但是系统将内存写入内存的值不等于我的输入值。这是代码:
double a,b;
printf("--------\n"); //seperate lines
scanf("%ld",&a);
printf("--------\n");
scanf("%ld",&b);
printf("%d %d",a,b);
如果我输入1和2,则CMD返回正确,但是B = -858993460这是我已经尝试过的:
使用scanf_s使用float或int而不是double,使用scanf(“%i或%i或%li或%lf或%lf或%e或%e或%g),使用fflush(stdin)清除键盘缓冲区,在b中阅读首先,尝试所有可能的组合。无论我做什么,第二个价值总是错误的
。
I try to read-in 2 values using scanf() in C, but the values the system writes into memory are not equal to my entered values. Here is the code:
double a,b;
printf("--------\n"); //seperate lines
scanf("%ld",&a);
printf("--------\n");
scanf("%ld",&b);
printf("%d %d",a,b);
If I enter 1 and 2, CMD returns a correct, but b = -858993460 Here is what I already tried:
using float or int instead of double, using scanf_s, using scanf("%d or %f for %i or %li or %lf or %e or %g ), using fflush(stdin) to clear keyboard buffer, reading in b first, trying like all possible combinations. I found out that there is a problem with the length of double on 32 bit OS, so that you are forced to use scanf("%lf", &f) to read in a double. No matter what I do, second value is always wrong.
I use MS VS express 2012 for Desktop on Windows 7 32 bit OS.
发布评论
评论(7)
使用
%lf
格式指定读读二:Wikipedia具有不错的参考指定器。
您需要使用
%lf
格式指定符来打印结果:Use the
%lf
format specifier to read a double:Wikipedia has a decent reference for available format specifiers.
You'll need to use the
%lf
format specifier to print out the results as well:据我所知,
%d
表示decadic,这是没有小数点的数字。如果要加载双重值,请使用%lf
转换(长float)。对于printf,由于相同的原因,您的值是错误的,%d
仅用于整数(如果您知道自己在做什么)数字。例子:
As far as i know
%d
means decadic which is number without decimal point. if you want to load double value, use%lf
conversion (long float). for printf your values are wrong for same reason,%d
is used only for integer (and possibly chars if you know what you are doing) numbers.Example:
您正在使用错误的格式序列
double
,应使用%lf
而不是%ld
:You are using wrong formatting sequence for
double
, you should use%lf
instead of%ld
:printf
中的格式指定词应为%f
fordouble
datatypes,因为float
datatyles最终转换为double> double
printf
中的数据类型。没有任何规定可以打印
float
数据。请在此处找到讨论:正确的格式指定器Format specifier in
printf
should be%f
fordoubl
datatypes sincefloat
datatyles eventually convert todouble
datatypes insideprintf
.There is no provision to print
float
data. Please find the discussion here : Correct format specifier for double in printf扫描第二个值时,请使用此代码行:
scanf(“%lf”,& b);
还用%LF替换所有%LD。
这是与输入流缓冲区有关的问题。您也可以使用fflush(stdin);在第一次扫描以清除输入缓冲区后,然后第二个SCANF将按预期工作。另一种方法是放置getch();或getChar();第一个SCANF系列后的功能。
Use this line of code when scanning the second value:
scanf(" %lf", &b);
also replace all %ld with %lf.
It's a problem related with input stream buffer. You can also use fflush(stdin); after the first scanning to clear the input buffer and then the second scanf will work as expected. An alternate way is place a getch(); or getchar(); function after the first scanf line.
正确的方法是:
Correct ways is:
使用
%LF
将帮助您解决此问题。使用 :
Using
%lf
will help you in solving this problem.Use :