View
251
Download
12
Category
Preview:
Citation preview
1
Cמבוא למחשב שפת
תרגילי חזרה
2
: מחשבון1תרגיל
קלט: תרגיל חשבוני המורכב ממספרים שלמים •עם פעולות חשבוניות ביניהם. התרגיל מסתיים ב
=. אפשריים רווחים בין המספרים לפעולותמספר יכול להיות שלילי, או חיובי. מספר חיובי •
עשוי להופיע עם + לפניודוגמאות קלט:•
123*34 =3*+4 * 8=
הנחה: הקלט תקין•
3
: מחשבון )המשך(1תרגיל
הקלט נעשה בשני שלבים:•קריאה של רצף תווים המייצגים מספר לתוך –
get_num_from_inputמחרוזת. הפונקציה הפיכת המחרוזת למספר שלם. הפונקציה –
getint
התוכנית מנוהלת ע"י לולאה שקוראת בכל •פעם מספר ופעולה. הלולאה נעצרת כאשר
‘=‘מופיע
4
get_num_from_inputהפונקציה // reads characters representing an int from input// writes to num_string a string representing a number// returns the next char in input which is not a spacechar get_num_from_input(char *num_string){
char c; //reads a char at a timeint i=1; scanf("%c",&c);while(is_space(c)) //skip possible spaces
scanf("%c",&c);num_string[0]=c; // may also be - or +scanf("%c",&c);while (is_digit(c)){
num_string[i++]=c;scanf("%c",&c);
}num_string[i]='\0';while(is_space(c))
scanf("%c",&c);return c;
}
5
getintהפונקציה
// converts a string into an integervoid getint(int *pn, char *num_string){
char c; //reads a char at a timeint sign=1; //the sign of the numberif(!is_digit(*num_string)){
sign = (num_string[0]=='-') ? -1 : 1;num_string++;
}for (*pn = 0; *num_string; num_string++)
*pn = 10* *pn + (*num_string-'0');*pn *= sign;
}
6
is_space ו is_digitהפונקציות
// returns true if c is a space characterint is_space(char c){
return c==' ' || c=='\n' || c=='\t';}
// returns true if c is a digit characterint is_digit(char c){
return c>='0' && c<='9';}
7
mainהפונקציה // program: calculator// Reads a sequence of operations with integers// and prints the result// the operation must end at '=', spaces are allowed #include <stdio.h>#include <ctype.h>
char get_num_from_input(char *);void getint(int *, char *);
int main(){
int num, result=0;char op,next_op;char snumber[11];printf
("Enter a computation with integers ending with =:\n");next_op=get_num_from_input(snumber);getint(&result,snumber);
8
mainהפונקציה do {
op=next_op;next_op=get_num_from_input(snumber);getint(&num,snumber);switch (op)
{case '+': result+=num; break;case '*': result*=num; break;case '-': result-=num; break;case '/': result/=num; break;case '%': result%=num; break;default:;}
} while(next_op!='=');printf("%d\n",result);return 0;
}
: מחשבון של מספרים 2תרגיל 9ממשיים
קלט: תרגיל חשבוני המורכב ממספרים ממשיים •עם פעולות חשבוניות ביניהם. התרגיל מסתיים ב
=. אפשריים רווחים בין המספרים לפעולותמספר יכול להיות שלילי, או חיובי. מספר חיובי •
עשוי להופיע עם + לפניומספר יכול להופיע עם או בלי נקודה עשרונית•דוגמאות קלט:•
12.34*56 =3.14*+4.00 * -8=
הנחה: הקלט תקין•
: מחשבון של מספרים 2תרגיל 10ממשיים )המשך(
הקלט נעשה בשני שלבים:•קריאה של רצף תווים המייצגים מספר לתוך –
get_num_from_inputמחרוזת. הפונקציה הפיכת המחרוזת למספר ממשי. הפונקציה –
getdouble
התוכנית מנוהלת ע"י לולאה שקוראת בכל •פעם מספר ופעולה. הלולאה נעצרת כאשר
‘=‘מופיע
11
get_num_from_inputהפונקציה // get_num_from_input: reads characters representing a floating // point number from input// writes to num_string a string representing a number// returns the next char in input which is not a spacechar get_num_from_input(char *num_string){
char c; //reads a char at a timeint i=1; scanf("%c",&c);while(is_space(c)) //skip possible spaces
scanf("%c",&c);num_string[0]=c; // may also be - or +scanf("%c",&c);while (is_digit(c)){
num_string[i++]=c;scanf("%c",&c);
}
get_num_from_inputהפונקציה 12)המשך(
if (c=='.') // decimal point{
num_string[i++]=c;scanf("%c",&c);while (is_digit(c)){
num_string[i++]=c;scanf("%c",&c);
}}num_string[i]='\0';while(is_space(c))
scanf("%c",&c);return c;
}
13
getdoubleהפונקציה
// converts a string into a floating pointvoid getdouble(double *pn, char *num_string){
char c; //reads a char at a timeint sign=1; //the sign of the numberdouble decimal_part; double decimal_fraction=0.1;if(!is_digit(*num_string)) // starts with + or -{
sign = (num_string[0]=='-') ? -1 : 1;num_string++;
}for (*pn = 0.0; is_digit(*num_string); num_string++)
*pn = 10.0* *pn + (*num_string-'0');
14
)המשך(getdoubleהפונקציה
if(*num_string=='.'){
++num_string;for (decimal_part=0.0; *num_string ; num_string++){
decimal_part += decimal_fraction*(*num_string-'0');decimal_fraction/=10;
}*pn+=decimal_part;
}*pn *= sign;
}
15
mainהפונקציה // program: calculator// Reads a sequence of operations with real numbers// and prints the result// the operation must end at '=', spaces are allowed #include <stdio.h>#include <ctype.h>char get_num_from_input(char *);void getdouble(double *, char *);int main(){
double num, result=0;char op, next_op;char snumber[11];printf("Enter a computation with real numbers ending with =:\n");next_op = get_num_from_input(snumber);getdouble(&result,snumber);
16
mainהפונקציה do {
op=next_op;next_op=get_num_from_input(snumber);getdouble(&num,snumber);switch (op) {case '+':
result+=num;break;
case '*':result*=num;break;
case '-':result-=num;break;
case '/':result/=num;break;
default:;}
}while(next_op!='=');printf("%lf\n",result);return 0;
}
: פירוק מספר שלם למכפלת 3תרגיל 17ראשוניים
קלט: מספר שלם חיובי•פלט: פרוק של המספר למכפלת מספרים •
ראשונייםדוגמה:•
1350 = 2 * 3^3 * 5^2
18
decomposeהפונקציה // decompose: decomposes n into a product of primes.// and prints the decomposition. n assumed positive// 1. find deg: highest power that 2 divides n// 2. print 2^deg, and divide n by 2^deg// 3. redo 1 and 2 for all odd integers, from 3 up to // square root of n void decompose(int n){
int i; // runs over divisors nint deg; // used as a degree of a primeif(n==1 || n==2 || n==3){
printf("%d = %d\n", n,n);return;
}printf ("%d =",n);if (!(n%2)) //n is even{
deg=degree(2,n); //the highest power that 2 divides nprintf (deg>1?" 2^%d ":" 2 ",deg);n /= pow_int(2,deg); // divide n by 2^degif (n>1) // if n is a power of 2, stop here
printf("*");}
19
)המשך(decomposeהפונקציה
for (i=3; n>1 && i*i <= n; i+=2) //run over odd integers {
if (!(n%i)) {
deg=degree(i,n);printf (deg>1?" %d^%d ":" %d ",i,deg);n /= pow_int(i,deg);if (n>1)
printf("*");}
}if (n>1) // n is divisible by a prime > sqrt(n)
printf (" %d",n);}
20
degreeהפונקציה // degree: returns the highest power that d divides n// Algorithm. start from exp = 0. keep deviding n by d,// until d no longer divides n. increment exp by 1// each time n is divided.int degree(int d, int n){
int exp=0; //power of dwhile (!(n%d)){
++exp;n/=d;
}return exp;
}
21
pow_intהפונקציה
// pow_int: returns a to the bth power//algorithm: a^b = a*a*...*a (b times). int pow_int(int a, int b){
int product=1;for (; b>0; --b)
product*=a;return product;
}
22
mainהפונקציה /* module: primedec.c
writes positive integers as a product of prime numbersprogram is teminated when typing 1 (or a smaller integer).Input: a sequence of positive integers, ended by 1.Output: For each number its decomposition to product of primes
*/#include <stdio.h>void decompose(int); int main(){
int number; // this number will be decomposed
do {printf("\nType a positive integer (1 or less to quit): ");scanf("%d", &number);if (number>0){
decompose(number);}
} while (number>1);return 0;
}
: פירוק מספר שלם למכפלת 4תרגיל 23ראשוניים בעזרת רקורסיה
קלט: מספר שלם חיובי•פלט: פרוק של המספר למכפלת מספרים •
ראשונייםדוגמה:•
1350 = 2 * 3 * 3 * 5 * 5
24
decomposeהפונקציה void decompose(int n, int min_div){
int div=min_div;if(n==1)
return;while(1){
if(n%div==0){
printf("%d",div);n/=div;if(n>1)
printf(" * ");decompose(n,div);return;
}div++;
}}
25
mainהפונקציה
int main(){
int number; // this number will be decomposed do{
printf("\nType a positive integer (1 or less to quit): ");scanf("%d", &number);if (number > 1){
printf("%d = ", number);decompose(number,2);
}}while (number > 1);return 0;
}
Recommended