非常基本的scanf程序无法在c中工作,无法理解为什么

问题描述

我是c语言的新手,我想学习如何使用scanf函数传递数据,然后使用printf函数向我展示打印结果。

这似乎应该很简单,但是我的预期输出与返回的内容不匹配。我的IDE是 vscode

#include <stdio.h>

#define pi 3.14159

int main()
{
    float size;
    float radius;
    scanf("this is the value : %f",&radius);
    size = (2/3)*pi*(radius*radius*radius);
    printf("%f",size);
    return 0;
}

here you can see what i inpute and what gets printed

在那之后,我去做一个简单的程序来理解这个概念,并且遇到了一个相似但又不同的问题。而不是现在每次都返回0,而是打印相同的常量

#include <stdio.h>

int main() 
{ 
    int a; 
    scanf("This is the value %d",&a); 
    printf("Input value read : a = %d",a); 
    return 0; 
}

Here you can see the output i get for the second program

关于出什么问题以及如何解决的任何想法?

解决方法

您似乎期望scanf打印一条消息,然后获取一个值:

scanf("this is the value : %f",&radius);

。只需通过打印消息然后使用scanf来获取值即可获得:

printf("Please insert the value :\n");
if (scanf ("%f",&radius) == 1)
{
    /* ... */
}

请注意检查scanf返回值,即成功获取的变量的数量。在这种情况下,我们希望它是1,因为唯一的格式说明符是%f

%f之前的消息使scanf实际上期望完全浮点数之前的字符串(包括空格)。仅插入输入数字(在您的示例中为5)使scanf丢弃输入,因为它与给定的字符串不匹配,并且没有存储任何值,因此radius保持未初始化状态,并且执行结果以未定义的行为。另外,前导2/3是用整数算术计算的,结果为0;结果为0。使用2.0/3.0来强制使用浮点运算。


涉及%d的测试的问题非常相似;您只会看到出于上述原因,scanf未写入a的随机未初始化值。