为什么 printf 不使用科学记数法? [英] Why is printf not using scientific notation?

查看:107
本文介绍了为什么 printf 不使用科学记数法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是一个常见问题.但是我找不到一个可靠的直接答案.

I understand that this is a common problem. However I can't find a solid straight answer.

16 ^ 54 = 1.0531229167e+65 (this is the result I want)

当我使用 pow(16,54) 时,我得到:

When I use pow(16,54), I get:

105312291668557186697918027683670432318895095400549111254310977536.0

105312291668557186697918027683670432318895095400549111254310977536.0

代码如下:

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

void main(){

   double public;
   double a = 16;
   double b = 54;
   public = (pow(a,b));

   printf("%.21f\n", public);
}

代码执行:

gcc main.c -lm

gcc main.c -lm

我做错了什么?

推荐答案

我做错了什么?

几件事:

  • 使用%.10e 格式作为科学记数法,使用printf 打印点后有十位数字,
  • 从你的 main 返回一个 int
  • 考虑不使用 public 来命名变量,以防您的程序需要移植到 C++,其中 public 是关键字.
  • Use %.10e format for scientific notation with printf for a printout with ten digits after the dot,
  • Return an int from your main,
  • Consider not using public to name a variable, on the chance that your program would need to be ported to C++, where public is a keyword.

以下是修复程序的方法:

Here is how you can fix your program:

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

int main(){

   double p;
   double a = 16;
   double b = 54;
   p = (pow(a,b));

   printf("%.10e\n", p);
   return 0;
}

ideone 演示.

这篇关于为什么 printf 不使用科学记数法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆