问题描述
#include <stdio.h>
void power(int *x,int *y);
int main()
{
int m,n;
printf("Enter the number and power :-");
scanf("%d%d",&m,&n);
power(&m,&n);
}
void power(int* x,int* y)
{
int i,result=1;
if(*y==0)
printf("The result = 1");
else
{
for(i=0; i<*y; i++)
{
result *= (*x);
}
printf("The result of %d^%d = %d",*x,*y,result);
}
}
10 ^ 10的结果是1410065408我不知道我在做什么错
解决方法
您显然有一个溢出,可能您的int
在32位上
使用long long
:
#include <stdio.h>
void power(long long *x,long long *y);
int main()
{
long long m,n;
printf("Enter the number and power :-");
scanf("%lld%lld",&m,&n);
power(&m,&n);
}
void power(long long* x,long long* y)
{
long long i,result=1;
if(*y==0)
printf("The result = 1");
else
{
for(i=0; i<*y; i++)
{
result *= (*x);
}
printf("The result of %lld^%lld = %lld",*x,*y,result);
}
}
编译和执行:
pi@raspberrypi:/tmp $ gcc -Wall p.c
pi@raspberrypi:/tmp $ ./a.out
Enter the number and power :-10 10
The result of 10^10 = 10000000000pi@raspberrypi:/tmp $
要确保使用64b int,可以使用int64_t
您使用int
作为结果,但不合适。您需要使用long
。 int
的大小为32位,最大符号值为2147483647。
您的给定程序使用4个字节的整数,该整数能够容纳-2,147,483,648到2,647之间的值,但是10 ^ 10太大而无法容纳它。
采用适当的类型(例如long long
)来获得如此大的结果将很容易解决您的问题(请注意注释作为对代码的解释):
#include <stdio.h>
// The function signature
void power(int *x,int *y);
int main(void) {
int bs,pw;
printf("Enter the value of base and power: ");
// Verifying the inputs
if (scanf("%d%d",&bs,&pw) != 2)
// If the values were incorrectly entered,then it returns
// with an error code without further actions
return 1;
power(&bs,&pw);
return 0;
}
// The function definition
void power(int *x,int *y) {
long long result = 1;
// Dereferencing and using assignment operator for self-multiplication with
// the dereferenced 'x'
for (int i = 0; i < *y; i++)
result *= *x;
printf("Results: %lld\n",result);
}
示例测试用例:
Enter the value of base and power: 10 10
Results: 10000000000
也可以在OnlineGDB上使用。
,#include <stdio.h>
void power(int *x,int *y);
int main()
{
int m,n;
printf("Enter the number and power :-");
scanf("%d%d",&n);
return 0;
}
void power(int* x,int* y)
{
int i;
long long result = 1;
if (*y == 0)
printf("The result = 1");
else
{
for (i = 0; i < *y; i++)
{
result *= (*x);
}
printf("The result of %d ^%d = %lld",result);
}
}