【问题标题】:C++ : extern variable inside namespace and printf vs coutC ++:命名空间内的外部变量和printf vs cout
【发布时间】:2013-05-09 17:04:45
【问题描述】:

我的 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;
}

=>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函数?

谢谢

【问题讨论】:

  • 真的有必要在kernel.cpp中包含kernel.h吗?
  • 不是报错,而是cpp文件中定义过多。您可以执行const double kernel::h=85.0(无需重新打开命名空间),或者仅执行const double h=85.0(如果您重新打开它)。你有点“两者都做了”,这是多余的。

标签: c++ namespaces printf extern cout


【解决方案1】:

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

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

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

或者直接使用std::cout就不会出现这种问题了

std::cout << kernel::h;

【讨论】:

    【解决方案2】:

    %d 用于整数,您尝试将double 打印为int。我想你想要%lflong float 双打?以前从未真正 printf'd a double。

    【讨论】:

    • 好吧,我的错!我真的很傻! %f 可以正常工作,你是对的 %d,它只适用于 int...非常感谢
    猜你喜欢
    • 2011-05-11
    • 1970-01-01
    • 2012-12-28
    • 2020-10-12
    • 2017-10-05
    • 2015-05-13
    • 1970-01-01
    • 2020-08-12
    • 1970-01-01
    相关资源
    最近更新 更多