大家看这个程序结果为什么不对

来源:百度知道 编辑:UC知道 时间:2024/05/22 12:53:24
#include<iostream>
#include<stdlib.h>
using namespace std;
main()
{
int space=0,word=0,num=0,other=0;
char c,string[81];
gets(string);
for(int i=0;(c=string[i])!='\0';i++)
{ c=string[i];
if(c==' ') space+=1;
else if(c>='0'&&c<='9') num+=1;
else if((c>='a'&&c<='z')||(c>='A'&&c<='Z')) word+=1;
else other+=1;
}
cout<<"空格:"<<space<<endl;
cout<<"字母:"<<word<<endl;
cout<<"数字:"<<num<<endl;
cout<<"其他:"<<other<<endl;
system("pause");
}
当对space,other,num,word都不给初值0的时候,num和word的结果是对的,而那两个就不对了,为什么啊

#include<iostream>
#include<stdlib.h>
using namespace std;
main()
{
int space=0,word=0,num=0,other=0;
char c,string[81];
gets(string);
for(int i=0;(c=string[i])!='\0';i++)//这里就要求四个变量要先初始化,不初始化怎么可以加、减呢?
{ c=string[i];
if(c==' ') space+=1;
else if(c>='0'&&c<='9') num+=1;
else if((c>='a'&&c<='z')||(c>='A'&&c<='Z')) word+=1;
else other+=1;
}
cout<<"空格:"<<space<<endl;
cout<<"字母:"<<word<<endl;
cout<<"数字:"<<num<<endl;
cout<<"其他:"<<other<<endl;
system("pause");

//你上面的程序有错误?哈哈,看不出来...功力不够...

我试过了,没什么问题吖

space,other,num,word应该赋初值0的

不给的时候,它们的值不可预期,有可能对,有可能不对

没有什么好说的