我打算让用户键只有正整数值,但我意识到输出是错误的。例如,我输入的最大值是100.6,显示的最大值只有100.我相信问题来自atoi。任何人都可以查看我的代码并告诉我什么是错的?
#include<iostream>
#include<string>
using namespace std;
int main()
{
const int SIZE = 12;
string month[SIZE] = { "Jan", "Feb", "Mar","April","May","June","July","August","Sept","October","Nov","Dec"};
string highestMonth, lowestMonth;
char temp[SIZE];
double rainFall[SIZE], total = 0.0, average, highest, lowest;
bool flag;
int i = 0;
do{
flag = false;
cout << "Enter rainfall for " << month[i] << " : ";
cin >> temp;
for (int j = 0; j < strlen(temp); j++)
{
if (!isdigit(temp[j]))
{
if (temp[j] == '.')
continue;
cout << "Enter positive integer value only" << endl;
flag = true;
break;
}
}
if (flag == false)
{
rainFall[i] = atoi(temp);
total += rainFall[i];
i++;
}
} while (i < SIZE);
average = total / 12.0;
lowest = rainFall[0];
lowestMonth = rainFall[0];
for (int i = 1; i < SIZE; i++)
{
if (rainFall[i] < lowest)
lowest = rainFall[i];
lowestMonth = rainFall[i];
}
highest = rainFall[0];
highestMonth = rainFall[0];
for (int i = 1; i < SIZE; i++)
{
if (rainFall[i]>highest)
highest = rainFall[i];
highestMonth = rainFall[i];
}
cout << "Total rainfall:" << total << endl;
cout << "Average:" << average << endl;
cout << "Highest:" << highest << " in " << highestMonth << endl;
cout << "Lowest:" << lowest << " in " << lowestMonth << endl;
system("pause");
return 0;
}
答案 0 :(得分:2)
atoi 将数字的字符串表示形式转换为整数,以便&#34; 100.6&#34;转换为100。
您可以使用 atof
答案 1 :(得分:1)
如果输入有小数点并且没有代码可以处理小数输入,则将flag
设置为true。
if (flag == false)
{
rainFall[i] = atoi(temp);
total += rainFall[i];
i++;
}
如果flag
为false,则此代码处理输入,但如果flag
为真,则没有类似的代码来处理小数。