【发布时间】:2018-05-19 12:32:44
【问题描述】:
我确实在下面的代码中注释了问题出在哪里,当调用 pow 函数时,exp 参数变得疯狂。代码的目标是接收用户输入并求解表达式 x/(1+t)^n。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
float val();
float pow();
float val(float x, int n, float t) {
float res = 0;
for (int i = 0; i < n; i++) {
printf("exp = %d\n", i+1); // real value exp start equals 1
res += x / pow(1 + t, i+1);
}
return res;
}
float pow(float base, int exp) {
int i = 0;
float res = 1;
printf("exp = %d", exp); // here starts the problem
if (exp == 1) {
return base;
}
while (i < exp) {
res *= base;
i++;
printf("i = %d\n", i);
printf("exp = %d\n", exp);
getchar();
}
return res;
}
main() {
int n;
float x, t, res;
printf("type x,n,t\n");
scanf("%f %d %f", &x, &n, &t);
res = val(x, n, t);
printf("VAL = %f\n", res);
}
输出:
type x,n,t
6
2
2
exp = 1
exp = 1074266112i = 1
exp = 1074266112
i = 2
exp = 1074266112
发生了什么事伙计们? 感谢您的关注:)
【问题讨论】:
-
有一个标准库函数
pow,你应该给你的函数起个不同的名字以避免链接冲突 -
好建议!!确实改变了浮动功率(浮动基数,int exp)希望一个不存在了:)
标签: c function parameter-passing