C/C++整数除法以及保留小数位的问题 | 设置输出宽度 | 设置左对齐
【摘要】
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a,b;
...
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a,b;
cin>>a>>b;
int C = a / b;
cout<<C<<endl;
double e = a, f = b;
double D = e / f;
cout<<setprecision(2)<<fixed<<D<<endl;
return 0;
}
____
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
代码分析:
整数除法用 “/”的话得到的是一个整数(得到小数的话自动去掉小数位只保留整数位)
- 1
解决方法:
先将两个数转化为double类型,再进行“/”除法
保留小数位数,则用cout<<setprecision(2);其中2表示保留2位小数
seprecision函数的使用要搭配**<iomanip>**头文件
setw(int); //设置显示宽度
setiosflags(ios::left) //设置左对齐
setiosflags(ios::right) //设置右对齐
- 1
- 2
- 3
- 4
- 5
- 6
- 7
//设置左对齐输出,空格在后
cout<<setiosflags(ios::left)
<<setw(5)<<10<<endl
<<setw(5)<<100<<endl
<<setw(5)<<1000<<endl;
//设置右对齐输出,空格在前
cout<<setiosflags(ios::right)
<<setw(5)<<10<<endl
<<setw(5)<<100<<endl
<<setw(5)<<1000<<endl;
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
文章来源: positive.blog.csdn.net,作者:墨理学AI,版权归原作者所有,如需转载,请联系作者。
原文链接:positive.blog.csdn.net/article/details/84623352
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)