當代碼運行時,FtoC()
函數中的cin
函數被忽略,而ctemp
的值默認爲0
。我已經得到了代碼運行期望使用其他代碼(不同的循環),但我真的很想了解這種錯誤的機制,並得到這樣做的工作。Cin不會暫停(忽略)用戶輸入
#include <cstdlib>
#include <iostream>
using namespace std;
void threeint();
void FtoC();
int main()
{
threeint();
FtoC();
return 0;
}
void FtoC()
{
double ctemp = 0, ftemp = 0;
cout << "Please enter the temperature in Celsius which you would like to be\
converted to Fharenheit." << endl;
cin >> ctemp;
ftemp = ((ctemp * (9/5)) + 35);
cout << ctemp << " degrees celsius is " << ftemp << " in fahrenheit" << endl;
}
void threeint()
{
int x = 0, bigint = 0, smlint = INT_MAX, avgint = 0, index = 0;
cout << "Input as many integers as you like and finalise by entering any
non-integer input" << endl;
while (cin >> x)
{
if (x > bigint)
bigint = x;
if (x < smlint)
smlint = x;
++index;
avgint += x;
}
cout << "The largest integer is " << bigint << ".\t" << "The smallest
integer is " << smlint << ".\t";
cout << "The average of all input is " << (avgint/index) << endl;
}
如果'double'或'int'提取失敗,您從不檢查'cin'的狀態。 –
無關但是(9/5)'不會做你認爲它做的事。 (提示:那個結果恰好是1,如果你感到驚訝,[見這裏](http://mathworld.wolfram.com/IntegerDivision.html)) – Borgleader