这是一个可重现的C++程序:
#include <RInside.h>
#include <Rcpp.h>
int main (int argc, char *argv[])
{
RInside R (argc, argv);
SEXP ans = R.parseEval ("m <- 40.702147");
Rcpp::NumericVector v (ans);
for (int i=0; i< v.size(); i++)
{
std::cout << "In C++ element " << i << " is " << v[i] << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
Makefile在这里:
## -*- mode: make; tab-width: 8; -*-
##
## Simple Makefile
##
## TODO:
## proper configure for non-Debian file locations, [ Done ]
## allow RHOME to be set for non-default R etc
## comment this out if you need a different version of R,
## and set set R_HOME accordingly as an environment variable
R_HOME := $(shell R RHOME)
sources := $(wildcard *.cpp)
programs := $(sources:.cpp=)
## include headers and libraries for R
RCPPFLAGS := $(shell $(R_HOME)/bin/R CMD config --cppflags)
RLDFLAGS := $(shell $(R_HOME)/bin/R CMD config --ldflags)
RBLAS := $(shell $(R_HOME)/bin/R CMD config BLAS_LIBS)
RLAPACK := $(shell $(R_HOME)/bin/R CMD config LAPACK_LIBS)
## if you need to set an rpath to R itself, also uncomment
#RRPATH := -Wl,-rpath,$(R_HOME)/lib
## include headers and libraries for Rcpp interface classes
RCPPINCL := $(shell echo 'Rcpp:::CxxFlags()' | $(R_HOME)/bin/R --vanilla --slave)
RCPPLIBS := $(shell echo 'Rcpp:::LdFlags()' | $(R_HOME)/bin/R --vanilla --slave)
## include headers and libraries for RInside embedding classes
RINSIDEINCL := $(shell echo 'RInside:::CxxFlags()' | $(R_HOME)/bin/R --vanilla --slave)
RINSIDELIBS := $(shell echo 'RInside:::LdFlags()' | $(R_HOME)/bin/R --vanilla --slave)
## compiler etc settings used in default make rules
CXX := $(shell $(R_HOME)/bin/R CMD config CXX)
CPPFLAGS := -Wall $(shell $(R_HOME)/bin/R CMD config CPPFLAGS)
CXXFLAGS := $(RCPPFLAGS) $(RCPPINCL) $(RINSIDEINCL) $(shell $(R_HOME)/bin/R CMD config CXXFLAGS)
LDLIBS := $(RLDFLAGS) $(RRPATH) $(RBLAS) $(RLAPACK) $(RCPPLIBS) $(RINSIDELIBS)
all: $(programs)
@test -x /usr/bin/strip && strip $^
run: $(programs)
@for p in $(programs); do echo; echo "Running $$p:"; ./$$p; done
clean:
rm -vf $(programs)
rm -vrf *.dSYM
runAll:
for p in $(programs); do echo "Running $$p"; ./$$p; done
Run Code Online (Sandbox Code Playgroud)
该计划的输出:
In C++ element 0 is 40.7021
Run Code Online (Sandbox Code Playgroud)
问题是该值40.702147被"截断"为40.7021.
我想要它充实.
出路是什么?
值本身未被截断(a),cout输出流使用输出的默认值.
您可以查看iomanip标题以查找强制特定输出格式的方法,例如:
std::cout << std::setprecision (9) << v[i] << '\n';
Run Code Online (Sandbox Code Playgroud)
这个完整的程序:
#include <iostream>
#include <iomanip>
int main (void) {
double d = 40.702147;
std::cout << d << '\n';
std::cout << std::setprecision (9) << d << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
40.7021
40.702147
Run Code Online (Sandbox Code Playgroud)
(a):请记住,如果它不能完全表示为IEEE754双精度值,它可能会被截断但在这里不是这种情况 - 双精度具有大约15个十进制数字的精度,而你只看到6个.