C码字练习.05.判断,分歧 - 北方连萌

C码字练习.05.判断,分歧

Switch和break

循环跳出之比较

FortranC意味
exitbreak;跳出循环体至其直下
cyclecontinue;跳至从头开始下一次循环

Goto在C中不被推荐使用(但是用起来很香)

C中break的另一用途

跳出switch,结束在case中的选择,若在该执行的case中没加break语句,那么在执行该case之后该case之下的case也会被执行,直到遇到break语句

#include<stdio.h>
#include<ctype.h>
int main(void)
{
   int i;

   printf("Try to enter a word starting with 3 or a/A.\n");
   while ((i =  getchar()) != '#')
   {
      switch (tolower(i)) //<ctype.h>库中的tolower()可强制转换成小写
      {
      case '3':
         printf("aaa\n");
         break;
      case 'a':
         printf("333\n");
         break;      
      default:
         printf("Try to enter a word starting with 3 or a/A.\n");
         break;
      }
      //以下的while语句用以抛弃首字母之后的字母直至行末
      while (getchar() != '\n')
      {
         continue;
      }
      printf("next (# to end)\n");
   }
   printf("Bye.\n");

   
   return 0;
}
Try to enter a word starting with 3 or a/A.
Adsl  
333
next (# to end)
3devs
aaa
next (# to end)
8ds
Try to enter a word starting with 3 or a/A.
next (# to end)
ii
Try to enter a word starting with 3 or a/A.
next (# to end)
#
Bye.

字数统计

#include<stdio.h>
#define STOP '#'
int main(void)
{
   char ch;
   int ch_ct = 0, r_ct = 0, sp_ct = 0, sr_ct = 0, prev;

   printf("Please enter some phrases.\n");
   while((ch = getchar()) != STOP)
   {
      ch_ct++;
      if(ch == '\n')
      {
         r_ct++;
      }
      if(ch == ' ')
      {
         sp_ct++;
      }
   }
   prev = ch;

   if(prev != '\n')
   {
      sr_ct = 1;
   }
   printf("There are %d character(s), %d space(s), %d row(s) and %d partial row(s) in phrases entered.\n", ch_ct - sp_ct - r_ct, sp_ct, r_ct, sr_ct);
   return 0;
}
Please enter some phrases.
This is a
test
phrase.
!@#
There are 20 character(s), 2 space(s), 3 row(s) and 1 partial row(s) in phrases entered.

获取和打印字符的另一种方法

即getchar()和putchar()
每次仅处理一个字符

另外由于C的缓冲输入机制,按回车健把输入的内容存进缓冲区执行时回车键会把自己也存进缓冲区
以下的程序的缺陷也在于此,若在输入"#"之前回车会出现一些问题

#include<stdio.h>
#define STOP '#'
int main(void)
{
   char ch;
   int i = 0;
   
   printf("Please enter a string ending with #.\n");
   printf("For each character in the string, it will be shown as \"character(ASCII value)\".\n");

   while((ch = getchar()) != STOP)
   {
      printf("%2c(%3d) ", ch, ch);
      if(++i % 6 == 0)
      {
         putchar('\n');
      }
   }
   
   return 0;
}
Please enter a string ending with #.
For each character in the string, it will be shown as "character(ASCII value)".
FTYFJTYTF%frbhdrrnhdfmfdgndfjhyg;[j;t.h;.er;h.d;frh.;pe.bsdgksimVGTCVF565P+:{>#
 F( 70)  T( 84)  Y( 89)  F( 70)  J( 74)  T( 84) 
 Y( 89)  T( 84)  F( 70)  %( 37)  f(102)  r(114) 
 b( 98)  h(104)  d(100)  r(114)  r(114)  n(110) 
 h(104)  d(100)  f(102)  m(109)  f(102)  d(100) 
 g(103)  n(110)  d(100)  f(102)  j(106)  h(104) 
 y(121)  g(103)  ;( 59)  [( 91)  j(106)  ;( 59)
 t(116)  .( 46)  h(104)  ;( 59)  .( 46)  e(101)
 r(114)  ;( 59)  h(104)  .( 46)  d(100)  ;( 59)
 f(102)  r(114)  h(104)  .( 46)  ;( 59)  p(112)
 e(101)  .( 46)  b( 98)  s(115)  d(100)  g(103)
 k(107)  s(115)  i(105)  m(109)  V( 86)  G( 71)
 T( 84)  C( 67)  V( 86)  F( 70)  5( 53)  6( 54)
 5( 53)  P( 80)  +( 43)  :( 58)  {(123)  >( 62)

奇偶数分别统计

#include<stdio.h>
int main(void)
{
   int n;
   int s1 = 0;
   int s2 = 0;
   double a1 = 0;
   double a2 = 0;
   int c1 = 0;
   int c2 = 0;

   printf("请输入一个整数(输入0结束输入过程)。\n");
   scanf("%d", &n);
   while(n != 0)
   {
      if(n % 2 == 0)
      {
         s2 += n;
         a2 = (double)s2 / ++c2;
      }
      else
      { 
         s1 += n;
         a1 = (double)s1 / ++c1;
      }
      printf("请输入一个整数(输入0结束输入过程)。\n");
      scanf("%d", &n);
   }
   printf("输入了%d个偶数,其平均数(不含0)是%.2f。\n", c2, a2);
   printf("输入了%d个奇数,其平均数是%.2f。\n", c1, a1);
   
   return 0;
}
请输入一个整数(输入0结束输入过程)。
1
请输入一个整数(输入0结束输入过程)。
2
请输入一个整数(输入0结束输入过程)。
3
请输入一个整数(输入0结束输入过程)。
4
请输入一个整数(输入0结束输入过程)。
5
请输入一个整数(输入0结束输入过程)。
6
请输入一个整数(输入0结束输入过程)。
7
请输入一个整数(输入0结束输入过程)。
8
请输入一个整数(输入0结束输入过程)。
9
请输入一个整数(输入0结束输入过程)。
10
请输入一个整数(输入0结束输入过程)。
11
请输入一个整数(输入0结束输入过程)。
0
输入了5个偶数,其平均数(不含0)是6.00。
输入了6个奇数,其平均数是6.00。

换标点

"If...else" style

#include<stdio.h>
int main(void)
{
   char ch;
   int i = 0, c = 0;

   printf("Please enter a phrase ending with # (or just a #) if you want to ehd this program.\n");
   printf("Now \".\" will be overwritten by \"!\" , and \"!\" will be overwritten by \"!!\" in phrase entered.\n");
   while((ch = getchar()) != '#')
   {
       if(ch == '.')
       {
           ch = '!';
           c++;
           
       }
       else if(ch == '!')
       {
           putchar('!');
           c++;
       }
       putchar(ch);
   }
   printf("\nThere are %d place(s) overwritten in total.\n", c);
   
   return 0;
}
Please enter a phrase ending with # (or just a #) if you want to ehd this program.
Now "." will be overwritten by "!" , and "!" will be overwritten by "!!" in phrase entered.
SSS...
SSS!!!
AAA!!
AAA!!!!
#

There are 5 place(s) overwritten in total.

"Switch...case" style

#include<stdio.h>
int main(void)
{
   char ch;
   int i = 0, c = 0;

   printf("Please enter a phrase ending with # (or just a #) if you want to end this program.\n");
   printf("Now \".\" will be overwritten by \"!\" , and \"!\" will be overwritten by \"!!\" in phrase entered.\n");
   while((ch = getchar()) != '#')
   {
       switch (ch)
       {
       case '.':
           ch = '!';
           c++;
           break;
       case '!':
           putchar('!');
           c++;
           break;       
       default:
           break;
       }
       putchar(ch);
   }
   printf("\nThere are %d place(s) overwritten in total.\n", c);
   
   return 0;
}
Please enter a phrase ending with # (or just a #) if you want to end this program.
Now "." will be overwritten by "!" , and "!" will be overwritten by "!!" in phrase entered.
SSS...
SSS!!!
AAA!!
AAA!!!!
#

There are 5 place(s) overwritten in total.

特定字符串的计数

使用continue捕捉下一个字符

#include<stdio.h>
int main(void)
{
   char ch;
   int c = 0;

   printf("Please enter a phrase ending with # (or just a #) if you want to end this program.\n");
   while((ch = getchar()) != '#')
   {
      if (ch == 'e')
         continue;
      if (ch == 'i')
         c++;
   }
   printf("There are %d \"ei\"(s) in total.\n", c);
   
   return 0;
}
Please enter a phrase ending with # (or just a #) if you want to end this program.
Receive your eieio award.#
There are 3 "ei"(s) in total.

分段函数

Base defined

$$\begin{array}\ y=\begin{cases}BASE\cdot x\quad(0 \leq x \leq 40) \\\\ 40\cdot BASE+15 x\quad(x>40)\end{cases}\end{array}$$

$$\begin{array}\ t=\begin{cases}0.15 y\quad(0 \leq y \leq 300) \\\\ 45+0.2(y-300)\quad(300 \leq y \leq 450) \\\\ 75+0.25(y-450)\quad(y>450)\end{cases}\end{array}$$

$$\begin{array}\ r=y-t\end{array}$$

#include<stdio.h>
#define BASE 10
#define RATE1 0.15
#define RATE2 0.20
#define RATE3 0.25

int main(void)
{
   double px, y, t, r;
   int x;

   a:
   printf("x = ");
   scanf("%lf", &px);
   x = (int)px; //如果输入了小数则对其去尾

   if(x < 0)
   {
      printf("请输入非负数。\n");
      goto a;
   }
   else if(x >= 0 && x <= 40)
   {
      y = BASE * x;
   }
   else
   {
      y = 40 * BASE + (x - 40) * 1.5 * BASE;
   }

   printf("y = %.2f\n", y);

   if(y >= 0 && y <= 300)
   {
      t = RATE1 * y;
   }
   else if(y > 300 && y <= 450)
   {
      t = 300 * RATE1 + (y - 300) * RATE2;
   }
   else
   {
      t = 300 * RATE1 + 150 * RATE2 + (y - 450) * RATE3;
   }

   r = y - t;
   printf("t = %.2f\n", t);
   printf("r = %.2f\n", r);

   return 0;
}
x = 60
y = 700.00
t = 137.50
r = 562.50

Choosing bases (input content confined)

添加了一些选项
对常见的输入错误可以反映并提示用户输入符合条件的内容

使用类似菜单的东西增加了交互性的同时也为排错增加了难度

#include<stdio.h>
#define RATE1 0.15
#define RATE2 0.20
#define RATE3 0.25

int main(void)
{
   double px, y, t, r, BASE;
   int x, ch;

   printf("**************************************************\n");
   printf("Choose a BASE.\n");
   printf("1) 8.75           2) 9.33           3) 10.00\n");
   printf("4) 11.20          5) quit                   \n");
   printf("**************************************************\n");
   
   s:
   printf("Please enter a number between 1~5.\n");
   if (scanf("%d", &ch) == 1 && ch >= 1 && ch <= 5)
   {
      goto sw;
   }
   else
   {
      fflush(stdin); //清空输入缓冲区,防止反复读取造成无限循环(键盘输入通常是行缓冲输入,按下回车键才刷新缓冲区)
      goto s;
   }

   sw:
   switch (ch)
   {
   case 1:
      BASE = 8.75;
      break;
   case 2:
      BASE = 9.33;
      break;
   case 3:
      BASE = 10.00;
      break;
   case 4:
      BASE = 11.20;
      break;
   case 5:
      goto e;      
   default:
      goto s;
   }

   a:
   printf("Time\n");
   while(scanf("%lf", &px) != 1)
   {
      printf("Please enter a number.\n");
      printf("Time\n");
      fflush(stdin);
   }
   x = (int)px;

   if(x < 0)
   {
      printf("Time must be greater than or equal to 0!\nPlease retry.\n");
      goto a;
   }
   else if(x >= 0 && x <= 40)
   {
      y = BASE * x;
   }
   else
   {
      y = 40 * BASE + (x - 40) * 1.5 * BASE;
   }

   printf("Wage(Gross)\n%.2f\n", y);

   if(y >= 0 && y <= 300)
   {
      t = RATE1 * y;
   }
   else if(y > 300 && y <= 450)
   {
      t = 300 * RATE1 + (y - 300) * RATE2;
   }
   else
   {
      t = 300 * RATE1 + 150 * RATE2 + (y - 450) * RATE3;
   }

   r = y - t;
   printf("Tex\n%.2f\n", t);
   printf("Wage(Net)\n%.2f\n", r);

   e:
   printf("Bye.");
   return 0;
}
**************************************************
Choose a BASE.
1) 8.75           2) 9.33           3) 10.00
4) 11.20          5) quit
**************************************************
Please enter a number between 1~5.
5555
Please enter a number between 1~5.
55555
Please enter a number between 1~5.
5555555
Please enter a number between 1~5.
opqrst
Please enter a number between 1~5.
3
Time
??
Please enter a number.
Time
.
Please enter a number.
Time
gt
Please enter a number.
Time
60
Wage(Gross)
700.00
Tex
137.50
Wage(Net)
562.50
Bye.

输出素数

依次判断

#include<stdio.h>
#include<stdbool.h> //使用户可以用bool声明布尔型变量
int main(void)
{
   double j;
   int i, n, c = 0;
   bool p;
   st:
   printf("请输入一个大于等于2的整数。\n");
   if(scanf("%lf", &j) == 1 && j >= 2 && j - (int)j == 0)
   {
      printf("开始打印2到%d之间的素数。\n", (int)j);
      for(n = 2; n <= (int)j; n++) //确定搜寻范围
      {
         for(i = 2, p = true; i * i <= n; i++)
         //此处运用布尔型变量,将初始值设为真,在接下来的循环判断中如果找到约数(整除成立),则将其设为假
         {
            if(n % i == 0)
               p = false;
         }
         //在循环后加上一个判断,如果循环结束布尔值一直维持真,那么这个数是素数
         if(p)
         {
            printf("%-7d ", n);
            ++c;
            if(c % 10 == 0)
               printf("\n");
         }
      }
   }
   else
   {
      fflush(stdin);
      goto st;
   }

   return 0;
}
请输入一个大于等于2的整数。
1000
开始打印2到1000之间的素数。
2       3       5       7       11      13      17      19      23      29
31      37      41      43      47      53      59      61      67      71
73      79      83      89      97      101     103     107     109     113
127     131     137     139     149     151     157     163     167     173
179     181     191     193     197     199     211     223     227     229
233     239     241     251     257     263     269     271     277     281
283     293     307     311     313     317     331     337     347     349     
353     359     367     373     379     383     389     397     401     409
419     421     431     433     439     443     449     457     461     463
467     479     487     491     499     503     509     521     523     541
547     557     563     569     571     577     587     593     599     601
607     613     617     619     631     641     643     647     653     659
661     673     677     683     691     701     709     719     727     733     
739     743     751     757     761     769     773     787     797     809
811     821     823     827     829     839     853     857     859     863
877     881     883     887     907     911     919     929     937     941
947     953     967     971     977     983     991     997

素数筛

Fortran版写法:

见此

#include<stdio.h>
#include<stdbool.h>
#define SIZE 1000 
int main(void)
{
   int a[SIZE], i, j, c = 0;
   bool b[SIZE];

   for(i = 0; i < SIZE; i++)
   {
      b[i] = true;
      a[i] = i + 1;
   }

   for(j = 2; i <= SIZE; j++)
   {
      for(i = j; i < SIZE; i++)
      {
         if(a[i] % j == 0)
            b[i] = false;
      }
   }

   for(i = 1; i < SIZE; i++)
   {
      if(b[i])
      {
         printf("%-7d ", a[i]);
         ++c;
         if(c % 10 == 0)
            printf("\n");
      }
   }

   return 0;
}
2       3       5       7       11      13      17      19      23      29      
31      37      41      43      47      53      59      61      67      71
73      79      83      89      97      101     103     107     109     113
127     131     137     139     149     151     157     163     167     173
179     181     191     193     197     199     211     223     227     229
233     239     241     251     257     263     269     271     277     281     
283     293     307     311     313     317     331     337     347     349
353     359     367     373     379     383     389     397     401     409
419     421     431     433     439     443     449     457     461     463
467     479     487     491     499     503     509     521     523     541
547     557     563     569     571     577     587     593     599     601
607     613     617     619     631     641     643     647     653     659     
661     673     677     683     691     701     709     719     727     733
739     743     751     757     761     769     773     787     797     809
811     821     823     827     829     839     853     857     859     863
877     881     883     887     907     911     919     929     937     941     
947     953     967     971     977     983     991     997

添加新评论

电子邮件地址不会被公开,评论内容可能需要管理员审核后显示。