C++中 cin 与 cout 的用法

本文介绍了C++中整数在十进制、八进制、十六进制之间的转换方法,并展示了如何在代码中设置浮点数的精度。通过实例代码演示了十六进制输出、不同基数表示以及如何调整浮点数显示的精确度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


整数的基数:dec(十进制) ,   oct(八进制),    hex(十六进制)  。

具体实现见代码:

/**************************************************/
#include <iostream>
using namespace std;
int main()
{
  cout.setf(ios::hex, ios::basefield);  //十六进制
  cout << 100; // this displays 64
  return 0;
}
/**************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
   int n;
   cout << "Enter a decimal number: ";   //输入一个十进制的数
   cin >> n;
   cout << n << " in hexadecimal is: "   //用十六进制表示为
        << hex << n << '\n'
        << dec << n << " in octal is: "  //用八进制表示为
        << oct << n << '\n'
        << setbase( 10 ) << n << " in decimal is: "  //十进制表示为
        << n << endl;
   return 0;
}
/**************************************************/

/********以整数开方为例介cin、cout中设置精度的用法************/
/*      
        设置浮点数精度:
        setprecision (必须带参数)
        precision (无参数时返回当前设置的精度)
        设置后,对以后的输出都有效。
        
*/
#include<iostream>
#include<ctype.h>
#include<iomanip>
#include<cmath>
using namespace std;
int main() {
    double ans=sqrt(3.0);
    cout<<setiosflags(ios ::fixed)
        <<"Square root of 2 with precisions 0-9\n"
        <<"precision se by the "
        <<"precision member function:"<<endl;
    for(int i=0; i<=9; i++) {
        cout.precision(i);
        cout<<ans<<endl;
    }
    cout<<"precision now is: "<<cout.precision()<<endl;
    for(int i=0; i<=9; i++) {
        cout<<setprecision(i)<<ans<<endl;
    }
    return 0;
}

/**************************************************/

基本都是根据别人的分享总结的,不是很全,以后会更新的。。。。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值