1、阅读下列程序,然后上机运行验证输出结果,并回答下列问题。 #include <iostream> using namespace std; void showflags(long f) { long i = 0x8000; for(; i; i=i>>1) { if(i&f) cout<<"1"; else cout<<"0"; } cout<<endl; } int main() { showflags(cout.flags()); cout<<"x_width="<<cout.width()<<endl; cout<<"x_fill="<<cout.fill()<<endl; cout<<"x_precision="<<cout.precision()<<endl; cout<<123<<" "<<123.45678<<endl; cout<<"-----------------------------"<<endl; cout<<"* * * x_width=10,x_fill= ,x_precision=4 * * *"<<endl; cout.width(10); cout.precision(4); cout<<123<<" "<<123.45678<<" "<<234.567<<endl; -------------------① cout<<"x_width="<<cout.width()<<endl; cout<<"x_fill="<<cout.fill()<<endl; cout<<"x_precision="<<cout.precision()<<endl; cout<<"-----------------------------"<<endl; cout<<"* * * x_width=10,x_file=&,x_precision=4 * * *"<<endl; cout.fill('&'); cout.width(10); cout<<123<<" "<<123.45678<<endl; cout.setf(ios::left); cout.width(10); cout<<123<<" "<<123.45678<<endl; cout<<"x_width="<<cout.width()<<endl; cout<<"x_fill="<<cout.fill()<<endl; cout<<"x_precision="<<cout.precision()<<endl; showflags(cout.flags());----------------------------------------------------------② cout.setf(ios::right|ios::unitbuf); showflags(cout.flags());----------------------------------------------------------③ return 0; } 问题一:①处的输出结果是什么,为什么? 问题二:②处的输出结果是什么,为什么? 问题三:③处的输出结果是什么,为什么? (提示:在x_flags变量中left=0x0002,right=0x0004,unitbuf=0x2000)
时间: 2023-09-20 08:12:39 浏览: 47
答案如下:
问题一:①处的输出结果为:
0000001001011011
x_width=0
x_fill=
x_precision=6
123 123.457
-----------------------------
* * * x_width=10,x_fill= ,x_precision=4 * * *
123 123.4568 234.6
x_width=10
x_fill=
x_precision=4
-----------------------------
这是因为,初始时,cout的各个标志位的状态为默认状态,即x_width=0,x_fill=' ',x_precision=6。接着,输出了123和123.45678两个数,输出的间隔为默认的空格,所以输出为"123 123.457"。然后,通过setw(10)和setprecision(4)来设置输出宽度和精度,再次输出了123、123.45678和234.567三个数,输出的间隔为默认的空格,因此输出为"123 123.4568 234.6"。最后,输出了当前的x_width、x_fill和x_precision的值,分别为10、空格和4。
问题二:②处的输出结果为:
* * * x_width=10,x_fill=&,x_precision=4 * * *
x_width=10
x_fill=&
x_precision=4
-----------------------------
这是因为,通过cout.fill('&')将x_fill设置为'&',通过setw(10)和setprecision(4)来设置输出宽度和精度,然后分别输出了123和123.45678两个数,输出的间隔为'&',因此输出为"123&&&&&&&123.457"。接着,通过cout.setf(ios::left)设置左对齐,再次输出了两个数,输出的间隔为'&',因此输出为"123&&&&&&&123.457 "。最后,输出了当前的x_width、x_fill、x_precision的值以及cout的各个标志位的状态。
问题三:③处的输出结果为:
0000001011010010
这是因为,通过cout.setf(ios::right|ios::unitbuf)同时设置了右对齐和unitbuf标志位,因此输出了对应的二进制数。其中,right=0x0004,unitbuf=0x2000,它们的二进制数分别为0000000000000100和0010000000000000,进行按位或运算后得到0000001011010010。