简体   繁体   English

C语言:为什么在int声明的变量中输入浮点数时结果会变化

[英]C language : why when input a float number in an int declared variable the result varries

using a simple code: 使用简单的代码:

#include <stdio.h>

int main(int argc, int **argv)
{
    int A, B, C, D, E, F; 
    printf ("input 1  : ");
    scanf ("%d", &A);
    printf ("input 2 : ");
    scanf ("%d", &B);
    C = A + B;
    D = A - B;
    E = A * B;
    F = A / B;
    printf ("sum  : %d\n", C);
    printf ("difference : %d\n", D);
    printf ("product  : %d\n", E);
    printf ("quotient : %d\n", F);
    return 0;
}

My question is as such, in the first scanf [ps I know I can use other input methods its for a project] if you input a float/double number such as 1.3 or 20.5 the sum and difference are quite random for me,anyone can explain to me why the results are what they are? 我的问题是这样的,在第一个scanf中[ps我知道我可以在项目中使用其他输入法]如果输入浮点数/双精度数(例如1.3或20.5),则总和和差对我来说是相当随机的,任何人都可以向我解释为什么结果是真实的?

Continuing from the comments, you must always validate all input (especially user input). 从注释继续,您必须始终验证所有输入(尤其是用户输入)。 All input functions provide a return. 所有输入函数都提供返回。 The scanf family returns the match count , the number of successful conversions processed based on the number of format specifiers in the format string . scanf系列返回匹配计数 ,根据格式字符串格式说明符的数量,成功处理的转换数量。 You use that to validate your input. 您可以使用它来验证您的输入。 Eg, at minimum: 例如,至少:

#include <stdio.h>

int main(int argc, int **argv)
{
    int A, B, C, D, E, F; 
    printf ("input 1  : ");
    if (scanf ("%d", &A) != 1) {
        fprintf (stderr, "error: invalid input - A.\n");
        return 1;
    }
    printf ("input 2 : ");
    if (scanf ("%d", &B) != 1 || B == 0) {
        fprintf (stderr, "error: invalid input - B.\n");
        return 1;
    }
    C = A + B;
    D = A - B;
    E = A * B;
    F = A / B;
    printf ("sum  : %d\n", C);
    printf ("difference : %d\n", D);
    printf ("product  : %d\n", E);
    printf ("quotient : %d\n", F);
    return 0;
}

note: your "quotient" will always be the result of integer division and truncated accordingly. 注意:您的"quotient"将始终是整数除法的结果,并相应地被截断。

The first scanf() , if the input has a decimal point will stop at the decimal point and leave it to be read on the next operation. 如果输入中有小数点,则第一个scanf()会停在小数点,并留待下一个操作读取。 For input of 1.3 , this means A will get the value 1 , and the .3 will remain in the input stream to be read. 对于1.3输入,这意味着A将获得值1 ,而.3将保留在要读取的输入流中。 This is because of the %d format - which tells scanf() to expect an integral value, and to stop on any characters that do appear in any representation of an integral value. 这是因为%d格式-告诉scanf()期望一个整数值,并停止出现在任何以数值表示形式中的字符。 A decimal point is one such character that is not used in the representation of an integral value. 小数点就是一个这样的字符,在整数值的表示中不使用小数点。

The next operation ( scanf("%d", &B) ) immediately encounters the decimal point and returns, without changing B . 下一个操作( scanf("%d", &B) )立即遇到小数点并返回,而不更改B

Since B is not initialised at all (before, during, or after the scanf("%d", &B) ) in the program, any subsequent attempt to access its value gives undefined behaviour. 由于B根本没有初始化(在程序中的scanf("%d", &B)之前,之中或之后),因此任何随后的尝试访问其值的尝试都将导致未定义的行为。 Among other things, this can mean the value of B is indeterminate. 除其他外,这可能意味着B的值不确定。 From what you describe, for your setup, that results in "random" input. 根据您的描述,对于您的设置,将导致“随机”输入。

If you're expecting to read input that looks like floating point values (eg that contains a decimal point) either read as floating point (eg %f format, and variables of a floating point type) or read a whole line (eg using fgets() ) and check the contents of the line BEFORE trying to read integral values from it. 如果您希望读取的输入看起来像浮点值(例如,包含小数点),则可以将其读取为浮点(例如, %f格式和浮点类型的变量),也可以读取整行(例如,使用fgets() ),并在尝试从该行读取整数值之前检查该行的内容。

If you insist on using scanf() , check its return value. 如果您坚持使用scanf() ,请检查其返回值。 On the second call of scanf() in your scenario, scanf() will return 0 rather than 1 (since it has read no values, rather than the one value the format string specified). 在您的场景中第二次调用scanf()时, scanf()将返回0而不是1 (因为它没有读取任何值,而不是指定格式字符串的一个值)。 Which is an indication that something has gone wrong reading the input. 这表明读取输入出现了问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么(double + int)的结果为0(C语言) - why result of (double + int) is 0 (C language) 将浮点表达式的结果存储到 C 中的 int 变量中的正确方法是什么? - What is the correct way of storing the result of a float expression into an int variable in C? 为什么用浮点数除以整数会导致浮点数? - Why does dividing a int with a float result in a float? 如何/何时在C语言中声明函数中的静态变量? - how/when is a static variable in a function declared within C language? 为什么 int function 即使没有在 C 中首先声明它们也能工作 - Why int function works even when they're not declared first in C C语言:为什么int变量可以存储char? - C Language: Why int variable can store char? 为什么打印这个浮点数会导致 c 中的答案错误 - Why does the printing of this float number result in the wrong answer in c 将双精度数赋值给C中的int变量的非直观结果 - Nonintuitive result of the assignment of a double precision number to an int variable in C 为什么在转换为int时将浮点数在C中四舍五入? - Why does a float when converted to an int be rounded off below in C? 将 int 乘以 int 得到浮点数返回 0 语言是 C - Multiplying an int by an int to give a float is returning 0 language is C
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM