为什么在输入错误类型的值作为输入时,变量“b"总是赋值为 1? [英] Why, on entering a wrong type of value as input, the variable "b" is always assigned to 1?

查看:69
本文介绍了为什么在输入错误类型的值作为输入时,变量“b"总是赋值为 1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个简单的代码中,

#include int main(void){国际a, b;scanf("%d %d",&a,&b);printf("\na 的值为:%d",a);printf("\nb 的值为:%d",b);}

当我输入错误类型的值作为输入时,变量 b 总是被分配为 1.我尝试添加另一个变量c"并在代码末尾打印其值,但变量b"仍然始终分配为 1.为什么?

解决方案

如果 scanf() 返回后 scanf() 参数的值未定义,如果转换是不成功,但最可能的行为是它保持不变.在这种情况下, b 未初始化,因此无论 scanf() 的行为如何,都可以具有任何值.

考虑:

#include int main(void){int a = -1, b = -1;scanf("%d %d",&a,&b);printf("\na 的值为:%d",a);printf("\nb 的值为:%d",b);返回 0 ;}

在这种情况下,如果转换失败,我希望 ab 都具有输入的值或 -1 - 即使这实际上不是必需的.

scanf() 返回转换和分配的参数数量.考虑:

#include int main(void){int a = 0, b = 0;int convert = scanf("%d %d",&a,&b) ;if( 转换 > 0 ){printf("\na 的值为:%d",a);if( 转换 > 1 ){printf("\nb 的值为:%d",b);}别的{printf("\nb 的值未定义");}}别的{printf("\na 的值未定义");}返回 0 ;}

对于您的测试输入 54test hello 它输出:

<前>45测试你好a 的值为:45b 的值未定义

In this simple code,

#include <stdio.h>
int main(void)
{
     int a, b;
     scanf("%d %d",&a,&b);
     printf("\nThe value of a is : %d",a);
     printf("\nThe value of b is : %d",b);
}

When I enter a wrong type of value as input, the variable b is always getting assigned to 1. I have tried to add another variable "c" and printed its value at the end of the code, but still the variable "b" is always assigned to 1. Why?

解决方案

If value of a scanf() argument after scanf() returns is undefined if the conversion was unsuccessful, but the most likely behaviour is that it remains unchanged. In this case b is uninitialised so could have any value regardless of the behaviour of scanf() .

Consider:

#include <stdio.h>
int main(void)
{
    int a = -1, b = -1;
    scanf("%d %d",&a,&b);
    printf("\nThe value of a is : %d",a);
    printf("\nThe value of b is : %d",b);

    return 0 ;
}

I would expect in this case both a and b to have either the entered value or -1 if the conversion fails - even though that is not actually required.

scanf() returns the number of arguments converted and assigned. Consider:

#include <stdio.h>
int main(void)
{
    int a = 0, b = 0;
    int convert = scanf("%d %d",&a,&b) ;
    if( convert > 0 )
    {
        printf("\nThe value of a is : %d",a);

        if( convert > 1 )
        {
            printf("\nThe value of b is : %d",b);
        }
        else
        {
            printf("\nThe value of b is undefined" );
        }
    }
    else
    {
        printf("\nThe value of a is undefined" );
    }

    return 0 ;
}

For your test input 54test hello it outputs:

45test hello

The value of a is : 45
The value of b is undefined

这篇关于为什么在输入错误类型的值作为输入时,变量“b"总是赋值为 1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆