C++中各种输出格式 如fixed、precision()、showpoint等

out<<fixed  //用一般的方式输出浮点型,例如C++程序在控制台显示大一点的数,显示的时候使用了科学计数法,使用该命令即可像一般的方式显示

cout.precision(2) //设置精确度为2,并返回上一次的设置。

cout.setf(iOS_base::showpoint)  //显示浮点数小数点后面的零。


更多格式说明

用来格式控制的。setf()是追加标志字的函数,而flags()是设置标志字
fixed标志是以定点形式显示浮点数showpoint标志是强制显示小数点precision就是精度,表示输出多少小数位。
试试这段代码你就知道了
#include <iostream.h>
#include <iomanip.h>
void main(void)
{
cout.setf(ios::fixed);
cout<<setprecision(2)<<(float)0.1<<endl;//输出0.10

cout.unsetf(ios::fixed);
cout<<setprecision(2)<<(float)0.1<<endl; //输出0.1
} 以下是一些常见的控制函数的:
dec 置基数为10 相当于"%d"
hex 置基数为16 相当于"%X"
oct 置基数为8 相当于"%o"
setfill(c) 设填充字符为c
setprecision(n) 设显示小数精度为n位
setw(n) 设域宽为n个字符
这个控制符的意思是保证输出宽度为n。如:
cout<<setw(3)<<1<<setw(3)<<10<<setw(3)<<100; 输出结果为
1 10100 (默认是右对齐)当输出长度大于3时(<<1000),setw(3)不起作用。
setioflags(ios::fixed) 固定的浮点显示
setioflags(ios::scientific) 指数表示
setiosflags(ios::left) 左对齐
setiosflags(ios::right) 右对齐
setiosflags(ios::skipws 忽略前导空白
setiosflags(ios::uppercase) 16进制数大写输出
setiosflags(ios::lowercase) 16进制小写输出
setiosflags(ios::showpoint) 强制显示小数点
setiosflags(ios::showpos) 强制显示符号
输出实例加源代码
// outfile.cpp -- writing to a file
#include <iostream>
#include <fstream>                  // for file I/O

int main()
{
    using namespace std;
    char automobile[50];
    int year;
    double a_price;
    double d_price;
    ofstream outFile;               // create object for output
    outFile.open("carinfo.txt");    // associate with a file
    cout << "Enter the make and model of automobile: ";
    cin.getline(automobile, 50);
    cout << "Enter the model year: ";
    cin >> year;
    cout << "Enter the original asking price: ";
    cin >> a_price;
    d_price = 0.913 * a_price;

// display information on screen with cout
    cout << fixed;
    cout.precision(2);
    cout.setf(ios_base::showpoint);
    cout << "Make and model: " << automobile << endl;
    cout << "Year: " << year << endl;
    cout << "Was asking $" << a_price << endl;
    cout << "Now asking $" << d_price << endl;

// now do exact same things using outFile instead of cout
    outFile << fixed;
    outFile.precision(2);
    outFile.setf(ios_base::showpoint);
    outFile << "Make and model: " << automobile << endl;
    outFile << "Year: " << year << endl;
    outFile << "Was asking $" << a_price << endl;
    outFile << "Now asking $" << d_price << endl;
     
    outFile.close();              // done with file
    // cin.get();
    // cin.get();
    return 0;
}
cout输出结果(图左侧窗口)和outFile输出结果(图右侧TXT文本文件)见图;该TXT文本是由outFile.open()关联的,文件位置一般在该可执行文件(源代码)所在的目录,文件名为carinfo,该文件也可能位于其他位置。

  • 23
    点赞
  • 86
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值