为什么我不能拒绝小数?(C++)
Why cant i reject Decimals? (C++)
使用此代码:
#include <iostream>
#include <iomanip>
using namespace std;
//Functions
int power(int base,int exp);
double energy(int z, int n);
//Main
int main() {
const double E0(13.6),hce(1.24E-6),e(1.6E-19);
int n1,n2,z;
double E;
cout << "**************************************" << endl;
cout << "Welcome to the energy level calculatorn" << endl;
cout << "Please enter the atomic number, z: " << endl;
cin >> z; //Ask for z
cout << "Please enter n for the initial energy level: " << endl;
cin >> n1; //Ask for n1
cout << "Please enter n for the final energy level: " << endl;
cin >> n2; //Ask for n2
while(cin.fail()||z<1||n1<1||n2<1){
cout << "nnnnnPlease enter non-zero integers only, try againnnnnnn" << endl;
cout << "**************************************" << endl;
cin.clear();
cin.ignore();
cout << "Please enter the atomic number, z: " << endl;
cin >> z; //Ask for z
cout << "Please enter n for the initial energy level: " << endl;
cin >> n1; //Ask for n1
cout << "Please enter n for the final energy level: " << endl;
cin >> n2; //Ask for n2
}
etc...
该程序只允许接受整数如果我输入一个小数,比如1.2,程序会拒绝1。但当它应该要求从键盘输入时,却使用2作为z?有人能帮忙吗?
由于您要求解释,当您输入1.2
时
cin >> z; //Successfully reads '1' into 'z'
cin >> n1; //Fails to read '.' into 'n1'. '.' remains the first character in the stream.
cin >> n2; //Fails to read '.' into 'n2'. '.' remains the first character in the stream.
然后循环回到循环的开头。
cin.clear(); //clears the fail flag from the two previous failed inputs
cin.ignore(); // ignores the '.'
cin >> z; //Reads '2' into 'z'. The stream is now empty.
然后程序在cin >> n1
上阻塞,等待在流中放置更多字符。
每次输入后,您应该查看输入是否失败。
cin>>n1;
if(cin.fail())
cin.ignore();
相关文章:
- C++将浮点指针值舍入为小数位数
- 从给定的 I 和 D 序列中形成最小数
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用 std::index_sequence 初始化具有固定大小数组成员的 POD 结构容器
- 计算 PI 最多 42 位小数
- 为什么我必须添加一个小数才能在C++中正确计算此数学
- 返回浮点数的小数位数
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 在数学上将浮点数四舍五入到 N 位小数
- 打印双精度的整个非小数部分
- 声明后,gcc 的动态大小数组是否与标准数组有效相同?
- 如何在C++中对OpenCV垫的小数进行四舍五入?
- 将 int 数组转换为带有小数C++的双精度数组
- Arduino如何制作返回固定大小数组的函数
- 从浮点数中删除小数部分但保留类型的有效方法
- 分配新的零大小数组可以具有有效价值吗?
- c++只关心2位小数,没有设置精度
- 有没有一种方法可以在不设置精度的情况下设置小数位数
- gcc c++编译器中的零大小数组
- 给出了一个数的确切除数(n),如何确定具有n个除数的最小数?