简体   繁体   English

当单个 for 循环中包含多个 scanf() 时会发生什么

[英]What happens when multiple scanf()s are included in a single for loop

I have written a code for comparing the triplet problem.我写了一个代码来比较三元组问题。 The problem statement is:问题陈述是:

Input: 2 arrays of size 3输入:2 个大小为 3 的数组

Task is to find their comparison points by comparing a[0] with b[0] , a[1] with b[1] , and a[2] with b[2] .任务是通过比较a[0]b[0]a[1]b[1]以及a[2]b[2]来找到它们的比较点。

If a[i] > b[i] , then Alice is awarded point.如果a[i] > b[i] ,则 Alice 获得分数。 If a[i] < b[i] then Bob is awarded the point.如果a[i] < b[i]则 Bob 获得积分。 If a[i] == b[i] then neither person receives the point.如果a[i] == b[i]则没有人得到分数。 Comparison points is the total points the person earned.比较积分是该人获得的总积分。 Given a and b determine their respective comparison points.给定ab确定它们各自的比较点。

The code I wrote is:我写的代码是:

 #include<stdio.h>
 void main(){   
       int i, alice[3], bob[3];
       int a = 0;
       int b = 0;
                                                                                                                                          
       for(i=0; i<3; i++){
                 scanf("%d", &alice[i]);
       }
       for(i=0; i<3; i++){
                 scanf("%d", &bob[i]); 
       }
       for(i=0; i<3; i++){ 
                if(alice[i] > bob[i])  
                       a++; 
                else if (alice[i] < bob[i]) 
                       b++;
       }   
      printf("%d %d", a, b);
 } 

But when I put the two scanf()s in one line,但是当我把两个 scanf() 放在一行时,

  for(i=0; i<3; i++){    
             scanf("%d", &alice[i]); 
             scanf("%d", &bob[i]); 
  }

The output is like 2 1 or 1 2 for all the inputs.对于所有输入,输出类似于 2 1 或 1 2。 Is it wrong to put two scanf() calls in a single for loop?将两个scanf()调用放在一个 for 循环中是错误的吗? I couldn't understand what is the reason behind this problem?我不明白这个问题背后的原因是什么? Would someone kindly explain the reason?有人会解释原因吗?

The first version reads three values for alice and then three values for bob .第一个版本读取alice三个值,然后读取bob三个值。 The second version reads one value for alice , then one for bob , and repeats that 3 times.第二个版本为alice读取一个值,然后为bob读取一个值,并重复 3 次。

If the entered numbers are 1, 2, 3, 4, 5, 6, then in the first example, alice gets 1, 2, 3 while bob gets 4, 5, 6;如果输入的数字是 1, 2, 3, 4, 5, 6,那么在第一个例子中, alice得到 1, 2, 3 而bob得到 4, 5, 6; in the second example, alice gets 1, 3, 5 while bob gets 2, 4, 6. Quite different results.在第二个例子中, alice得到 1, 3, 5 而bob得到 2, 4, 6。完全不同的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM