0

我对 printf 有一点问题,我不知道为什么!

=>内核.h

#ifndef KERNEL_H
#define KERNEL_H

namespace kernel
{
    extern const double h;
}

#endif // KERNEL_H

=>内核.cpp

#include <kernel.h>

namespace kernel
{
    const double kernel::h=85.0;
}

=>主.cpp

#include "kernel.h"
#include <iostream>
//#include <cstdio>//With cstdio, it is the same problem !

int main(int argc, char *argv[])
{

    using namespace kernel;

    double a = h;

    printf("printf a is %d\n",a);
    std::cout<<"std::cout a is " << a << std::endl;

    printf("printf h is %d\n",h);
    printf("printf kernel::h is %d\n",kernel::h);
    std::cout << "std::cout h is " << h << std::endl;

    return 0;
}

我在控制台上的输出是:

printf a is 0
std::cout a is 85
printf h is 0
printf kernel::h is 0
std::cout h is 85

为什么 printf 不起作用?因为它是一个C函数?

谢谢

4

2 回答 2

2

%d是整数,您试图将 a 打印doubleint. %lf我想你会想要long float双打?以前从未真正 printf'd a double 。

于 2013-05-09T17:05:54.963 回答
2

那是因为您将其打印为integer. 尝试%lg%lf

printf("printf kernel::h is %lg\n",kernel::h);

如果您打开警告,编译器会告诉您问题所在。-Wformat

或者只是使用std::cout,你不会有这种问题

std::cout << kernel::h;
于 2013-05-09T17:07:01.023 回答