为什么我不能拒绝小数?(C++)

Why cant i reject Decimals? (C++)

本文关键字:C++ 小数 不能 拒绝 为什么      更新时间:2023-10-16

使用此代码:

#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();