c - float 的平方

标签 c

编写一个 C 程序,要求用户从键盘输入一个 float ,然后打印出该数字的平方根,这就是问题。我做错了什么?

#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[])
{
double x, result;
printf("Enter a positive number.\n");
scanf("&f", &x);
result = sqrt(x);
printf("The square root of %f is %f.\n", x, result); 
return 0;
}

最佳答案

一元“&”运算符传递引用(到操作数变量的内存地址),而“%”运算符在 scanf 或 printf 上下文中,例如与变量类型的特定 ANSI C 符号结合使用,例如 double 类型的“lf”,被称为格式说明符。通过在两者之间放置一个整数值(如“%2lf”),可以指定要读取或打印的精度。 %f 指定 float 类型变量,其精度比 double 低。也请参阅文档。顺便说一下,在 C++ 中,精度是另外指定的。

所以:

double x, result;
printf("Enter a positive number.\n");
scanf("%f", &x); //<--- use %lf (for 'long float' ) instead of &f

关于c - float 的平方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42289147/

相关文章:

c - 如何在C中获得无穷大的值(value)? (尤其是整数值)

c - "true"(小写)是否已经是 Visual Studio 中的关键字?它可以被覆盖吗?

c - 循环读取 *.txt 文件

C——基本结构问题

c - header 开始 - 前向声明

c - out[i] = *(a_mat + i) 在 C 中做什么?

c - 警告 : "assignment discards ' const' qualifier from pointer target type"

c - 为什么 func() 和 func(void) 不同

c - 使用后明确清除/归零敏感变量是否明智?

c - 动态结构数组