C ++:命名空间内的extern变量和printf vs cout

时间:2013-05-09 17:04:46

标签: c++ namespaces printf extern cout

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

=> kernel.h当

#ifndef KERNEL_H
#define KERNEL_H

namespace kernel
{
    extern const double h;
}

#endif // KERNEL_H

=> kernel.cpp

#include <kernel.h>

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

=&GT; main.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函数吗?

由于

2 个答案:

答案 0 :(得分:2)

%d适用于整数,您尝试将double打印为int。我认为你需要%lf long float来获得双打?从来没有真正打印过双倍。

答案 1 :(得分:2)

这是因为您要将其打印为integer。 试试%lg%lf

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

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

或只是使用std::cout,你就不会遇到这类问题

std::cout << kernel::h;