C++心得笔记
今天也是巩固C++第三章知识的一天 ,做了一点题(基本上很基础,没有什么难度)。
请看其中之一题:
这道题注意在计算除法之前将数据转化成double类型,要不然两个long long 类型的数据做除法得到的也是long long 类型。
#include<iostream> int main() { using namespace std; long long globe; long long somebody; cout << "Enter the wolrd population:"; cin >> globe; cout << "Enter the population of the US:"; cin >> somebody; cout << "The population of the US is"; double percent; percent = (double)somebody / globe * 100; cout << percent << "% of the world population.\n"; return 0; }
后面还学到了一个新成员函数: std::cin.clear()
我们看下下面的代码:
#include<iostream>
int main()
{
using namespace std;
short int s1,s2;
cin>>s1;
cin>>s2;
cout<<"s1:"<<s1<<" s2:"<<s2<<endl;
return 0;
}
输入:31600000
输出:s1:32767 s2:0
s1 的值为
32767
这个数字转换为二进制是111111111111111
,是 short int 类型所能表示的最大的正数。s2 的值就很奇怪了,为 0.
为什么呢?
这是因为 std::cin 将 31600000 写入 short int 类型时发现了错误,将自己的
fail
成员设置为 true,之后继续调用 std::cin 不会读取缓冲区或触发用户输入。我们可以使用 std::cin.clear() 消除错误,使 std::cin 可以继续工作。
#include<iostream>
int main()
{
using namespace std;
short int s1,s2;
cin>>s1;
cin>>s2;
cout<<"s1:"<<s1<<" s2:"<<s2<<endl;
if (cin.fail() == true)
{
cout<<"cin.fail() == true\n";
cin.clear();
cout<<"cin can work know\n";
}
cin>>s2;
cout<<"s1:"<<s1<<" s2:"<<s2<<endl;
return 0;
}
输出如下: