编写一个 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/