关于isdigit函数的一个问题

凤梨头头 2014-03-23 03:51:08
C++primer plus课后的一个习题:
编写一个程序,最多将10个donation值读入到一个double数组。程序遇到非数字输入时将结束输入,并报告这些数字的平均值以及数组中有多少个数字大于平均值?
以下是给的答案:

#include <iostream>
#include<cctype>
int main()
{
using namespace std;

double sum=0,average=0;
double num[10];
int i=0,total=0;

double temp;

while(cin>>temp&&i<10&&!isdigit(temp))
//这里我有三个问题,希望大神帮我解答一下:
1、这里使用isdigit()函数判断是否为数字,这个函数不是针对字符的嘛,如果这里用这个函数,而且前面加了个‘!’的话,岂不是意味着不能输入48-57(对应的ASCII码是0-9)了吗?
2、而且为什么这里我输入a的时候,直接终止了程序,刚好满足题意输入非数字时候终止,输入a的话,a非数字,我觉得应该函数判定为假,即isdigit=0,!isdigit=1吗?
3、我明明设的temp是double型变量,不是字符呀,咋会输入字符a时候没有错误呢!

{
num[i]=temp;
sum+=num[i];
++i;
}

if(i!=0)
average=sum/i;

for(int j=0;j<i;++j)
if(num[j]>average)
++total;

cout<<"这些数字的平均值为"<<average<<endl;
cout<<"并且共有"<<total<<"个数字大于平均值。\n";

return 0;
}
...全文
163 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
morinstar 2015-03-12
  • 打赏
  • 举报
回复
我也在看这本书,比你晚了一年啊 同样仅仅搞懂了这个程序该怎么写,但是没理清那个isdigit为什么要在前面加一个! 很好奇楼主现在看primer ++ plus看到哪了, 我感觉从第五章开始,后面的编程习题越来越BT了
Ashily_1020 2014-03-23
  • 打赏
  • 举报
回复
function <cctype> isdigit int isdigit ( int c ); Check if character is decimal digit Checks whether c is a decimal digit character. Decimal digits are any of: 0 1 2 3 4 5 6 7 8 9 For a detailed chart on what the different ctype functions return for each character of the standard ASCII character set, see the reference for the <cctype> header. In C++, a locale-specific template version of this function (isdigit) exists in header <locale>. Parameters c Character to be checked, casted to an int, or EOF. Return Value A value different from zero (i.e., true) if indeed c is a decimal digit. Zero (i.e., false) otherwise.

64,660

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧