W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
我們可以使用break語句退出for循環(huán)。
此示例計算任意數(shù)量值的平均值:
#include <stdio.h>
#include <ctype.h> // For tolower() function
int main(void)
{
char answer = "N"; // Decision to continue the loop
double total = 0.0;
double value = 0.0;
unsigned int count = 0;
for( ;; ) // Indefinite loop
{
printf("\nEnter a value: "); // Prompt for the next value
scanf(" %lf", &value); // Read the next value
total += value; // Add value to total
++count; // Increment count of values
// check for more input
printf("Do you want to enter another value? (Y or N): ");
scanf(" %c", &answer); // Read response Y or N
if(tolower(answer) == "n") // look for any sign of no
break; // Exit from the loop
}
// Output the average to 2 decimal places
printf("\nThe average is %.2lf\n", total/count);
return 0;
}
上面的代碼生成以下結(jié)果。
使用break退出循環(huán)
#include <stdio.h>
int main(void)
{
float length, width;
printf("Enter the length of the rectangle:\n");
while (scanf("%f", &length) == 1)
{
printf("Length = %0.2f:\n", length);
printf("Enter its width:\n");
if (scanf("%f", &width) != 1)
break;
printf("Width = %0.2f:\n", width);
printf("Area = %0.2f:\n", length * width);
printf("Enter the length of the rectangle:\n");
}
return 0;
}
上面的代碼生成以下結(jié)果。
使用switch語句和break
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
printf("Please type in a letter; type # to end.\n");
while ((ch = getchar()) != "#")
{
if("\n" == ch)
continue;
if (islower(ch)) /* lowercase only */
switch (ch)
{
case "a" :
printf("a\n");
break;
case "b" :
printf("b\n");
break;
case "c" :
printf("c\n");
break;
case "d" :
printf("d\n");
break;
case "e" :
printf("e\n");
break;
case "f" :
printf("f\n");
break;
default :
printf("That"s a stumper!\n");
} /* end of switch */
else
printf("only lowercase letters.\n");
while (getchar() != "\n")
continue; /* skip rest of input line */
printf("Please type another letter or a #.\n");
} /* while loop end */
return 0;
}
上面的代碼生成以下結(jié)果。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: