我怎样才能通过检查条件来打破循环
how can i break a loop by checking a condition
我正在尝试对一些整数求和,当我按下“=”时,循环将终止并打印这些值的总和。我想在按相等之前给出 space。
#include <stdio.h>
int main()
{
int a, sum = 0;
char b;
while (1) {
scanf("%d", &a);
scanf(" %c", &b);
sum += a;
if(b == '=')
break;
}
printf("sum = %d", sum);
return 0;
}
您的问题是因为您在循环中执行了两次 scanf。
改为这样做:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int sum=0;
char a[10];
while(1){
scanf("%9s", a); // makes sure we won't have memory overflow
if(strcmp(a, "=") == 0)
break;
sum+=atoi(a);
}
printf("sum= %d",sum);
return 0;
}
两个scanf
,即
scanf("%d", &a);
scanf(" %c", &b);
将像这样工作:
输入:“1 2 3 4 =”
在第一个循环中,a
会变成1,b
会变成2。
在第二个循环中,a
会变成3,b
会变成4。
现在剩下的字符串是“=”
因此在第三个循环中没有要扫描的整数,因此 a
仍将具有值 3。b
将获得值 =
并且循环终止。
所以sum
是1+3+3,即7
您可以使用简单的 printf
语句来检查:
scanf("%d",&a);
printf("a=%d\n",a);
scanf(" %c",&b);
printf("b=%c\n",b);
Input:
1 2 3 4 =
Output:
a=1
b=2
a=3
b=4
a=3
b==
sum= 7
记住:始终检查 scanf
返回的值 - 例如:
if (scanf("%d",&a) != 1)
{
// Error - didn't scan an integer
// add error handling
...
}
所以你可以做到
while(1){
if (scanf("%d",&a) != 1)
{
// No integer found
// Add error handling...
// For now - just stop the loop
break;
}
sum+=a;
}
对于像“1 2 3 4 =”这样的输入,给出结果 10。
但是,像“1 2 3 4 HelloWorld”这样的输入也会给出结果 10,即任何非整数输入只会终止循环。如果您只希望循环在输入为 =
时终止,您可以扩展错误处理。
我正在尝试对一些整数求和,当我按下“=”时,循环将终止并打印这些值的总和。我想在按相等之前给出 space。
#include <stdio.h>
int main()
{
int a, sum = 0;
char b;
while (1) {
scanf("%d", &a);
scanf(" %c", &b);
sum += a;
if(b == '=')
break;
}
printf("sum = %d", sum);
return 0;
}
您的问题是因为您在循环中执行了两次 scanf。
改为这样做:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int sum=0;
char a[10];
while(1){
scanf("%9s", a); // makes sure we won't have memory overflow
if(strcmp(a, "=") == 0)
break;
sum+=atoi(a);
}
printf("sum= %d",sum);
return 0;
}
两个scanf
,即
scanf("%d", &a);
scanf(" %c", &b);
将像这样工作:
输入:“1 2 3 4 =”
在第一个循环中,a
会变成1,b
会变成2。
在第二个循环中,a
会变成3,b
会变成4。
现在剩下的字符串是“=”
因此在第三个循环中没有要扫描的整数,因此 a
仍将具有值 3。b
将获得值 =
并且循环终止。
所以sum
是1+3+3,即7
您可以使用简单的 printf
语句来检查:
scanf("%d",&a);
printf("a=%d\n",a);
scanf(" %c",&b);
printf("b=%c\n",b);
Input:
1 2 3 4 =
Output:
a=1
b=2
a=3
b=4
a=3
b==
sum= 7
记住:始终检查 scanf
返回的值 - 例如:
if (scanf("%d",&a) != 1)
{
// Error - didn't scan an integer
// add error handling
...
}
所以你可以做到
while(1){
if (scanf("%d",&a) != 1)
{
// No integer found
// Add error handling...
// For now - just stop the loop
break;
}
sum+=a;
}
对于像“1 2 3 4 =”这样的输入,给出结果 10。
但是,像“1 2 3 4 HelloWorld”这样的输入也会给出结果 10,即任何非整数输入只会终止循环。如果您只希望循环在输入为 =
时终止,您可以扩展错误处理。