以下是決策語句-
「if」關鍵字是用來在邏輯條件為真時執行一組語句。
if (condition){ Statement (s) }
以下範例檢查數字是否大於 50。
#include<stdio.h> main (){ int a; printf (“enter any number:</p><p>”); scanf (“%d”, &a); if (a>50) printf (“%d is greater than 50”, a); }
1) enter any number: 60 60 is greater than 50 . 2) enter any number 20 no output
if else語句接受True或False條件。
if (condition){ True block statement(s) } else{ False block statement(s) }
以下是檢查奇偶數的程式−
#include<stdio.h> main (){ int n; printf (“enter any number:</p><p>”); scanf (“%d”, &n); if (n%2 ==0) printf (“%d is even number”, n); else printf( “%d is odd number”, n); }
1) enter any number: 10 10 is even number
這裡的「if」被放置在另一個if(或)else 中-
if (condition1){ if (condition2) stmt1; else stmt2; } else{ if (condition3) stmt3; else stmt4; }
以下範例是列印給定數字中最大的3個數字。
#include<stdio.h> main (){ int a,b,c; printf (“enter 3 numbers”); scanf (“%d%d%d”, &a, &b, &c); if (a>b){ if (a>c) printf (“%d is largest”, a); else printf (“%d is largest”, c); } else { if (b>c) printf (“%d is largest”, b); else printf (“%d is largest”, c); } }
enter 3 numbers = 10 20 30 30 is largest
它是一個多路決策條件。
if (condition1) stmt1; else if (condition2) stmt2; - - - - - - - - - - else if (condition n) stmt n; else stmt x;
以下範例求二次方程式的根-
#include <math.h> main (){ int a,b,c,d; float r1, r2 printf ("enter the values a b c"); scanf (“%d%d%d”, &a, &b, &c); d= b*b – 4*a*c ; if (d>0){ r1 = (-b+sqrt(d)) / (2*a); r2 = (-b-sqrt(d)) / (2*a); printf (“root1 ,root2 =%f%f”, r1, r2); } else if (d== 0){ r1 = -b / (2*a); r2 = -b/ (2*a); printf (“root1, root2 = %f%f”, r1, r2); } else printf ("roots are imaginary”); }
1) enter the values of a b c : 1 4 3 Root 1 = -1 Root 2 = -3
它有助於從多個決策中選擇一個。
switch (expression){ case value1 : stmt1; break; case value2 : stmt2; break; - - - - - - default : stmt – x; }
#include<stdio.h> main (){ int n; printf (“enter a number”); scanf (“%d”, &n); switch (n){ case 0 : printf (“zero”) break; case 1 : printf (‘one”); break; default : printf (‘wrong choice”); } }
enter a number 1 One
以上是使用流程圖和程序來描述C語言中的決策概念的詳細內容。更多資訊請關注PHP中文網其他相關文章!