2013-02-08 66 views
-2

有了這個代碼:爲什麼不能拒絕小數? (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 calculator\n" << 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 << "\n\n\n\n\nPlease enter non-zero integers only, try again\n\n\n\n\n\n" << 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時,它應該是要求從鍵盤輸入? 任何人都可以幫忙嗎?

+5

「如果我輸入一個整數,比如1.2」err,呵呵?因爲當1.2是一個整數? – PlasmaHH 2013-02-08 15:12:41

+0

查找模數。 – David 2013-02-08 15:14:01

+1

...這就是當你毫不費力地檢查輸入操作的返回值時發生的情況。準備失去理智。 – 2013-02-08 15:14:37

回答

1

既然你問了一個解釋,當你進入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(); 
相關問題