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

int power(int base, int power){
    int result, i;
    result = 1;
    for (i=0; i < power; i++){
        result *= base;
    }/*for*/
    return result;
}/*power*/

int main (){
    int n = 0;

    int exponent = 0;
    while(n < 10){
        int answer = power(2, n);
        float neganswer = 1.0 / (power(2,n));

        printf("%d %d %g\n", exponent, answer, neganswer);

        exponent++;
        n++;
    }/*while*/
    return EXIT_SUCCESS;

}/*main*/

当该程序运行时,第二个函数从 1 变为 512,这会将其余列向右移动 2。我将如何排列这些列?谢谢。

4

5 回答 5

3

您可以将printf格式更改为:

printf("%d %3d %10g\n", exponent, answer, neganswer);

这会将参数格式化为特定宽度:

0   1          1
1   2        0.5
2   4       0.25
3   8      0.125
4  16     0.0625
5  32    0.03125
6  64   0.015625
7 128  0.0078125
8 256 0.00390625
9 512 0.00195312
于 2013-09-24T02:46:09.787 回答
2

不要从所有准备好的提供好的 2 答案中拿走,但有很多选项可用于printf().

// Nicely aligned with decimal point in the same place
// #  : Alternate form always prints `.`
// -  : Left justify the output.
// .* : Determine width from the next parameter which is `n`.
printf("%d %4d %#-.*f\n", exponent, answer, n, neganswer);
0    1 1.
1    2 0.5
2    4 0.25
3    8 0.125
4   16 0.0625
5   32 0.03125
6   64 0.015625
7  128 0.0078125
8  256 0.00390625
9  512 0.001953125
于 2013-09-24T03:37:11.130 回答
1

包含要写入标准输出的文本的 C 字符串。它可以选择包含嵌入的格式说明符,这些说明符被后续附加参数中指定的值替换,并根据请求进行格式化。

格式说明符遵循此原型:[参见下面的兼容性说明]

%[flags][width][.precision][length]specifier 

int main (){
    int n = 0;

    int exponent = 0;
    while(n < 10){
        int answer = power(2, n);
        float neganswer = 1.0 / (power(2,n));

        //modify printf("%d %d %g\n", exponent, answer, neganswer);
        printf("%d %4d %12g\n", exponent, answer, neganswer);

        exponent++;
        n++;
    }/*while*/
    return EXIT_SUCCESS;

}/*main*/

有关 printf 函数的更多信息,请参考以下链接

http://en.cppreference.com/w/c/io/fprintf

于 2013-09-24T02:55:31.187 回答
0

Take a look at my simple library: libtprint , the code there is quite easy to understand and you should get some basic ideas how to format columns with printf ().

Hope it helps !

于 2013-09-26T01:33:58.550 回答
0

尝试这个

    float neganswer = 1.0f / (power(2,n));

    printf("%d %3d %f\n", exponent, answer, neganswer);  
于 2013-10-15T20:55:02.740 回答