好吧,我正在做一項任務,並且感到沮喪。該任務讓我向用戶詢問一個數字,然後說出數字是偶數還是奇數,但如果用戶輸入「完成」,程序將退出。檢查Char/Int
所以我的問題是如何檢查字符/ int在同一時間的輸入,然後決定它是什麼。
// ConsoleApplication2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
bool isEven(int userAnswer);
using namespace std;
int userAnswer;
int main()
{
cout << "Which number would you like to check?" << endl;
cin >> userAnswer;
if (isEven(userAnswer) == false)
{
cout << userAnswer << " is a odd number." << endl;
}
else if (isEven(userAnswer) == true)
{
cout << userAnswer << " is a even number." << endl;
}
cin.get();
cin.get();
return 0;
}
bool isEven(int userAnswer)
{
if (userAnswer % 2 == 0)
{
return true;
}
else
{
return false;
}
}
'int userAnswer;'應該在'main'內部聲明而不是全局變量,並且您不需要'else if'而只需要'else',因爲只有兩種可能性函數調用('== false')和否定,更常用的是'!isEven(userAnswer)')。 – crashmstr
我收緊你先檢查「完成」字符串,然後如果沒有完成,將字符串轉換爲int並進行偶數/奇數檢查 – MokaT