我的程序阅读在中间刚刚好,但使用指针与下面和上面没有给出正确的价值,可以找到使用中间。
为什么在for循环中运行时低于(很可能也高于)为负?
我调用指针的方式是否正确?
/*
*
*Function pwrTwo has one parameter "middle" it reads the inout from the user
*to find below and above
*
*the function is used to find the highest power of two below middle
*and the lowest power of two above middle
*
*The function then returns the two values and they are printed in the
* the main function displayed as below<middle<above
*
*/
#include <stdio.h>
int pwrTwo(int m, int*above, int*below) {
int i = 0;
*above = 0;
*below = 0;
for (i = 2; *below < m; i += 1) {
*below = pow(2, i);
printf("%d,%d,%d\n", below, m, i); //my check to see if below middle and i are correct
}
for (i += 3; *above > m; i -= 1) {
*above = pow(2, i);
printf("%d,%d,%d\n", below, m, above); // checking again
}
return;
}
int main() {
int middle = 1;
int above = 0;
int below = 0;
while (middle > 0) {
printf("Please input a value:");
scanf("%d", &middle);
pwrTwo(middle, &above, &below);
printf("%d<%d<%d\n", below, middle, above);
}
}
最佳答案
你需要包括使用pow函数
因为您正在获取参数中的值,所以返回类型应该是void,
在这种情况下,你不需要使用指针,你只需要一个值表示下面,一个值表示上面,所以你只需要使用一个int..但是。。。
你可以这样做:
void pwrTwo(int m, int*above,int*below){
double log2m = log2(m);
*below = pow(2,floor(log2m));
*above = pow(2,ceil(log2m));
}
关于c - 输入上下的2的幂,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22523216/