代码已经通过了,但是不知道为什么要改,比如正确的代码一开始会输入一个n表示要输入n行测试数据,我定义i等于0,i小于n,然后用那个可以通过的代码测试,一直tm的少输出一行,必须把n改为n+1,才能通过
第四张图片标蓝的那一段代码,不写就输出10行,写上就输出9行,答案还都不对,if-else和单独用if为什么出来的结果不一样? 这到底是什么问题啊
//可以通过的代码
#include
#include
using namespace std;
int main(){
int n;
cin >> n;
for(int i=0;i1;i++){
char a[100];
int count=0;
fgets(a,100,stdin);
for(int j=0;j<100;j++){
if(a[j]=='\0') break;
if(a[j]!=' '){
count++;
}
if(a[j]==' ') break;
}
if(a[0]-a[count+1]==0)
cout << "Tie" << endl;;
if(a[0]-a[count+1]==1)
cout << "Player1" << endl;
if(a[0]-a[count+1]==-1)
cout << "Player2" << endl;
if(a[0]-a[count+1]==6)
cout << "Player2" << endl;
if(a[0]-a[count+1]==-6)
cout << "Player1" << endl;
if(a[0]-a[count+1]==5)
cout << "Player1" << endl;
if(a[0]-a[count+1]==-5)
cout << "Player2" << endl;
}
}
//不能通过的代码
#include
#include
using namespace std;
int main(){
int n;
cin >> n;
for(int i=0;i1;i++){
char a[100];
int count=0;
fgets(a,100,stdin);
for(int j=0;j<100;j++){
if(a[j]=='\0') break;
if(a[j]!=' ') count++;
if(a[j]==' ') break;
}
if(a[0]-a[count+1]==0){
cout << "Tie" << endl;;
}else if(a[0]-a[count+1]==1){
cout << "Player1" << endl;
}else if(a[0]-a[count+1]==-1)
cout << "Player2" << endl;
else if(a[0]-a[count+1]==6)
cout << "Player1" << endl;
else if(a[0]-a[count+1]==-6)
cout << "Player2" << endl;
else if(a[0]-a[count+1]==5)
cout << "Player1" << endl;
else if(a[0]-a[count+1]==-5)
cout << "Player2" << endl;
}
}
如果表达式不变,是没区别的。
问题的根源在于cin>>n的时候输入了回车符,回车符遗留再了输入缓存中,所以,在for循环中,fgets逐行读取的时候,读取的第一行实际是一个空行。
如果for循环中要用n,就需要在for循环前清空输入缓存。在cin >>n;后面添加如下代码:
cin >> n;
rewind(stdin); //添加这一句来清空输入缓存
if,else if和 if是不同的。
对于if,和else的使用
当满足if或else if的任意一条件时剩余的分支语句都不会执行(也不会进行判断是否满足条件)
对于都用if
语句会按顺序执行,满足要求则输出条件下的语句,不满足则下一个if继续判断
“多一少一”问题占程序员常犯错误的10%以上!
避免“多一少一”问题的方法之一是将比如<10甚至<5的数代入程序片断,掰手指头心算验证一下程序到底应该写为
x、x-1、x+1中的哪个?
<、<=、==、>、>=中的哪个?
清除输入缓存
C,rewind(stdin);
C++,cin.clear();cin.sync();