switch () .
:
switch () {
case __1: [__1]
case __2: [__2]
case __n: [__n]
[default: ]
}
1.6.
1.6 - switch
. . . .
, , . , , .
break return. break switch, for, while do. return , .
, , default, switch . default , .
: 4 .
#include <iostream.h>
int main () {
int a, b, res; char op;
cout <<" 1 : ; cin >> a;
cout <<"\n : ; cin >> op;
cout <<"\n 2 : ; cin >> b;
bool f = true;
switch (op){
case '+': res = + b; break;
case '-': res = a - b; break;
case '*': res = a * b; break;
case '/ ': res = a / b; break:
default: cout <<"\n "; f = false;
}
if (f) cout << "\n: " << res;
return 0;
}
1.9
(while)
: while ()
. . : , , .
. false, .
: y = x2 +1 .
#include <stdio.h>
int main() {
float Xn, Xk, Dx;
printf ( : );
scanf (%f%f%f, &Xn, &Xk, &Dx);
printf(| X | Y |\n); //
float X = Xn; //
|
|
while (X <= Xk){ //
printf (| %5.2f | %5.2f |\n, X, X*X + 1); //
X += Dx; //
}
return 0;
}
: .
#include <iostream.h>
int main(){
int num;
cout << \n : ;
cin >> num;
int half = num / 2; //
int div = 2; //
while (div < = half){
if (!(num % div)) cout << div << \n;
div++;
}
return 0;
}
while (true) while (1) - .
while . :
while (int x = 0){... /* */ }
(do while)
: do while ;
, , , . . , . , false - .
: .
#include <iostream.h>
int main(){
char answer;
do{
cout << \n !; cin >> answer;
}while (answer!= y);
return 0;
}
: X Eps :
( ), . , , . fabs(), <math.h>.
#include <stdio.h>
#include <math.h>
int main(){
double X, Eps; //
double Yp=1, Y; //
printf ( :);
scanf (%lf,%lf, &X, &Eps);
do Y = (Yp + X/Yp)/2 while (fabs (Y - Yp) >= Eps);
printf (\n %lf %lf, X, Y);
return 0;
}
(for)
:
for (; ; ) ;
, . .
, :
for (int i = 0, j = 2;...
int k, m;
for (k = 1, m = 0:...
, , .
, . true, . .
. .
|
|
for , .
: , 1 100.
for (int i = 1, s = 0; i < = 100; i++) s += i;
: y = x2 +1 :
#include <stdio.h>
int main(){
float Xn, Xk, Dx, X;
printf ( : );
scanf (%f%f%f, &Xn, &Xk, &Dx);
printf (\n| X | Y |);
for (X = Xn; X <= Xk; X += Dx)
printf(\n| %5.2f | %5.2f |,. X, X*X + 1);
return 0;
}
: .
#include <iostream.h>
int main(){
int num, half, div;
cout << \n : ; cin >> num;
for (half = num / 2, div = 2; div <= half; div++)
if (!(num % div)) cout << div <<\n;
return 0;
}
, , : , , .
while for , , :
for (b1; b2; b) ; b1; while (b2){ ; b3;}
.
, :
, , , ;
, , ;
;
, .
, :
do while , (, ).
while , , .
for ( - ).
1.10