2014-01-22 38 views
7

我知道這是一個常見問題。不過,我找不到一個明確的直接答案。爲什麼printf不使用科學記數法?

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

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

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

我做錯了什麼?

+1

所以你想要科學記數法? –

+0

也讀了關於'g'格式說明符。 –

回答

16

我在做什麼錯?

幾件事情:與printf與點後十位數字的打印輸出科學記數法

  • 使用%.10e格式,
  • 返回intmain
  • 考慮不使用public命名變量,因爲您的程序需要移植到C++,其中public是關鍵字。

這裏是你如何修復你的程序:

#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; 
} 

Demo on ideone.

+0

'公共'不是C中的關鍵字。:)雖然它的使用將會有問題,如果此代碼曾經移到C++ – abelenky

+0

@abelenky您是對的,我錯過了標籤。感謝您的更正! – dasblinkenlight

3

如果您需要科學記數法,你需要使用%eformat specifier

printf("%e\n", public); 
     ^^ 

而且,public在C++中是keyword,所以它會如果此代碼需要可移植,則最好避免使用其他任何關鍵字