문제

I need to show one element in scientific notation. The cout is located inside few loops and after setting the scientific notation, it affects the whole cout in the program. How can I switch back to regular notation.

This is the cout line:

cout << "Firing '" <<  fir << "' Time: " << time <<  " sec\nCorresponding altitude: " << scientific << alt << endl;

Only the variable alt should be shown in scientific notation.

I added cout.precision(2); and cout << fixed; after the line above but it also affects the other cout in the program.

I appreciate your help.

도움이 되었습니까?

해결책

Try something like this:

http://www.cplusplus.com/reference/ios/scientific/

cout << "Firing '" <<  fir << "' Time: " << time <<  " sec\nCorresponding altitude: ";
cout << std::scientific << alt << endl;
std::cout << std::defaultfloat; // C++ 11

... or ...

std::cout.unsetf ( std::ios::floatfield );   // C++ 98

See also:

c++ std::stream double values no scientific and no fixed count of decimals

http://www.cs.duke.edu/courses/cps149s/fall99/resources/n2.html

http://www.uow.edu.au/~lukes/TEXTBOOK/notes-cpp/io/omanipulators.html

다른 팁

Well, before you set the precision, you can store it with cout.precision(), in a variable. After you are done using the precision set to 2, reset back to where it was using the variable. i.e. cout.precision(precision) assuming "precision" is your variable.

example:

output:

1.2

1.234

#include <iostream>

using namespace std;

int precision;
float number = 1.234;

int  main(void)
{
  precision = cout.precision();
  cout.precision(2);
  cout << number << endl;
  cout.precision(precision);
  cout << number << endl;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top