gpt4 book ai didi

c - 在c中返回一个空白整数

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:46 25 4
gpt4 key购买 nike

我想编写一个幂函数,在要求时打印“无法计算 o^o”或返回整数结果。我怎样才能做到这一点?

我当前的代码打印错误语句和结果语句。我的代码:

#include <stdio.h>

double power(int base,int n);

int main() {
int no1,no2;


printf("Enter two numbers:\n");
printf("If you want to compute x^y enter x y\n");

scanf("%i%i", &no1, &no2);

printf("The value of %i^%i is %f", no1, no2, power(no1,no2));

return 0;
}

double power(int base, int n) {

double result = 1;

if( n == 0 && base == 0){
printf("Unable to compute 0^0\n");
}
else if( n == 0 && base != 0) {
result = 1;
}
else if( n>0 ){
for(n ; n>0 ; n--) {
result = result*base;
}
}
else if( n<0 ){
int temp = -n;

result = power(base,temp);
result = (float)1.0/result;
}

return result;
}

编辑:我其实是个新手。我在 K&R 的第一章中找到了幂函数。我想改进那个东西并找到了这个障碍。因此,请尽可能提供资源,以便我理解您的回答。

最佳答案

@BartoszMarcinkowski 给了你正确的答案,作为替代方案(如果你不能传递额外的变量)你可以返回 NAN 并用 isnan() 检查结果>.

In computing, NaN, standing for not a number, is a numeric data type value representing an undefined or unrepresentable value, especially in floating-point calculations.

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

double power(int base,int n);

int main(void)
{
double f;

f = power(2, 2);
if (isnan(f)) {
printf("Unable to compute power\n");
} else {
printf("%f\n", f);
}
return 0;
}

double power(int base, int n) {

double result = 1;

if( n == 0 && base == 0){
return NAN;
}
...
return result;
}

关于c - 在c中返回一个空白整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24571796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com