[英]C++ : extern variable inside namespace and printf vs 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;
}
=>的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函数?
谢谢
%d
是整数,您正在尝试将double
打印为int
。 我想您想让%lf
双倍的long float
吗? 从未真正打印过两倍。
那是因为您将其打印为integer
。 尝试%lg
或%lf
printf("printf kernel::h is %lg\n",kernel::h);
如果您打开警告 ,编译器会告诉您问题所在。 -Wformat
或仅使用std::cout
,您就不会遇到此类问题
std::cout << kernel::h;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.