如何在 n 可以 <200 的 c 中存储 pow(10,n) 整数值?
How to store pow(10,n) integer values in c where n can be <200?
#include<stdio.h>
#include<math.h>
int main(void)
{
long int n;
scanf("%d",&n);
n=pow(10,n);
printf("%ld\n",n);
solve(n);
return 0;
}
您需要使用 double
,而不是 long
(因为 1080 不适合 64 位 long
在 9223372036854775807). But read the floating point guide, since it is a very difficult subject (notice that floating point numbers are not the same as mathematical real numbers).
下方表示数字
你可以试试:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
int n = 0;
if (scanf("%d",&n)<1) { perror("scanf"); exit(EXIT_FAILURE); };
if (n < -256 || n > 256)
{ fprintf(stderr, "wrong exponent %d\n", n);
exit(EXIT_FAILURE); };
double x = pow(10.0,(double)n);
printf("ten power %d is %g\n", n, x);
return 0;
}
(我去掉了你没有定义的对solve
的调用;我测试了scanf
的成功和n
的范围)
对于更大的指数,您需要 bignums perhaps using GMPlib。
编译时不要忘记启用所有警告和调试信息。如果您使用 gcc -Wall -Wextra -g
编译原始代码,您将收到多次警告(每行几乎一个警告!)。
#include<stdio.h>
#include<math.h>
int main(void)
{
long int n;
scanf("%d",&n);
n=pow(10,n);
printf("%ld\n",n);
solve(n);
return 0;
}
您需要使用 double
,而不是 long
(因为 1080 不适合 64 位 long
在 9223372036854775807). But read the floating point guide, since it is a very difficult subject (notice that floating point numbers are not the same as mathematical real numbers).
你可以试试:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
int n = 0;
if (scanf("%d",&n)<1) { perror("scanf"); exit(EXIT_FAILURE); };
if (n < -256 || n > 256)
{ fprintf(stderr, "wrong exponent %d\n", n);
exit(EXIT_FAILURE); };
double x = pow(10.0,(double)n);
printf("ten power %d is %g\n", n, x);
return 0;
}
(我去掉了你没有定义的对solve
的调用;我测试了scanf
的成功和n
的范围)
对于更大的指数,您需要 bignums perhaps using GMPlib。
编译时不要忘记启用所有警告和调试信息。如果您使用 gcc -Wall -Wextra -g
编译原始代码,您将收到多次警告(每行几乎一个警告!)。