![](/img/trans.png)
[英]What is the use of \n while scanning two integers like in scanf("%d \n %d")?
[英]What is the meaning of while(scanf(“%d”,&n),n)?
鑒於以下代碼:
// this is a solution of uva 12279
#include<stdio.h>
int main()
{
int arr[10000],i,n,a,d=0,e=75;
while(scanf("%d",&n),n)// what's that means?
{
d++;
int c=0,b=0;
if(n==0)
return 0;
for(i=0;i<n;i++)
scanf("%d",&arr[i]);
for(i=0;i<n;i++)//this is for loop
{
if(arr[i]==0)
c++;
else
b++;
}
a=b-c;
printf("Case %d: %d\n",d,a);
}
return 0;
}
while(scanf("%d",&n),n)
什么意思?
在這種情況下
while(scanf("%d",&n),n)
使用了所謂的逗號運算符。
scanf("%d",&n),n
條件的值是變量n
的逗號運算符的第二個操作數的值。 如果n
不等於 0,則執行循環。
你可以通過以下方式想象它
start: scanf("%d",&n);
if ( n != 0 )
{
//...
goto start;
}
因此,在循環體中,除非重新賦值,否則變量n
不能等於 0。 結果來自所提供的代碼片段的這個語句
if(n==0)
return 0;
沒有意義。
按以下方式編寫循環條件會更正確
while ( scanf("%d",&n) == 1 && n != 0 )
來自 C 標准(6.5.17 逗號運算符)
2 逗號運算符的左操作數計算為空表達式; 在它的求值和右操作數的求值之間有一個序列點。 然后評估正確的操作數; 結果有其類型和值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.