C 中的函数 log(x) 总是给出相同的值
The function log(x) in C is always giving the same value
基本上,我试图使用 C 的 math.h 库中的 log(x) 函数求出数字的对数。但是,对于我为变量 x 输入的任何值,我最终得到了相同的答案:-722.259365。我下面的代码哪里有问题?
我是 C 的新手,所以请不要介意这是一个太愚蠢的错误。
#include<stdlib.h>
#include<math.h>
void PrintLogarithm(double x){
if(x<=0){
printf("Positive numbers only please.\n");
return;
}
double Result = log(x);
printf("%f\n", Result);
}
int main(){
double x;
scanf("%f", &x);
PrintLogarithm(x);
return 0;
}
我是 C 的新手,所以请不要介意这是一个太愚蠢的错误。
首先,您缺少一个包含
#include <stdio.h>
其次,您没有使用正确的格式说明符。您正在使用双打,因此您应该使用 %lf。如果你用 -Wformat
标志编译,你的编译器会通过告诉你这样的事情来警告你:
/cplayground/code.cpp:16:17: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%f", &x);
~~ ^~
%lf
如果您解决了这 2 个问题,您的程序最终应该会按预期运行。
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
void PrintLogarithm(double x) {
if(x<=0) {
printf("Positive numbers only please.\n");
return;
}
double Result = log(x);
printf("%lf\n", Result);
}
int main() {
double x;
scanf("%lf", &x);
PrintLogarithm(x);
return 0;
}
编辑:正如评论者所指出的,printf() 与 %lf 或 %f 作为格式说明符一起使用时效果很好。
基本上,我试图使用 C 的 math.h 库中的 log(x) 函数求出数字的对数。但是,对于我为变量 x 输入的任何值,我最终得到了相同的答案:-722.259365。我下面的代码哪里有问题?
我是 C 的新手,所以请不要介意这是一个太愚蠢的错误。
#include<stdlib.h>
#include<math.h>
void PrintLogarithm(double x){
if(x<=0){
printf("Positive numbers only please.\n");
return;
}
double Result = log(x);
printf("%f\n", Result);
}
int main(){
double x;
scanf("%f", &x);
PrintLogarithm(x);
return 0;
}
我是 C 的新手,所以请不要介意这是一个太愚蠢的错误。
首先,您缺少一个包含
#include <stdio.h>
其次,您没有使用正确的格式说明符。您正在使用双打,因此您应该使用 %lf。如果你用 -Wformat
标志编译,你的编译器会通过告诉你这样的事情来警告你:
/cplayground/code.cpp:16:17: warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat]
scanf("%f", &x);
~~ ^~
%lf
如果您解决了这 2 个问题,您的程序最终应该会按预期运行。
#include <stdlib.h>
#include <math.h>
#include <stdio.h>
void PrintLogarithm(double x) {
if(x<=0) {
printf("Positive numbers only please.\n");
return;
}
double Result = log(x);
printf("%lf\n", Result);
}
int main() {
double x;
scanf("%lf", &x);
PrintLogarithm(x);
return 0;
}
编辑:正如评论者所指出的,printf() 与 %lf 或 %f 作为格式说明符一起使用时效果很好。