Çàäà÷à 1. Ñêîëüêî ðàç â ïîñëåäîâàòåëüíîñòè âñòðå÷àåòñÿ ôðàãìåíò 1, 2, 1, 3.
 ôàéëå: 1, 2, 3, 1, 2, 1, 3, 1, 2, 1, 2, 1, 3, -17, 21, 1, 2, 1, 3, 0, -5
Ôðàãìåíò 1, 2, 1, 3 — 3 ðàçà
|
a |
b |
c |
d |
Øàã öèêëà 1 |
1 |
2 |
3 |
1 |
Øàã öèêëà 2 |
2 (èç b) |
3 (èç ñ) |
1 (èç d) |
2 (èç ôàéëà) |
#include <stdio.h>
int main(void) {
double a, b, c, d;
int counter = 0;
FILE *IN;
IN = fopen("input.txt", "r");
if (IN == NULL) {
printf("File not opened\n");
return -1;
}
/* If numbers less than 4 – result is 0 */
if (fscanf(IN, "%lf%lf%lf", &a, &b, &c) == 3) {
while (fscanf(IN, "%lf", &d) == 1) {
/* Now we have four numbers */
if ((a == 1) && (b == 2) && (c == 1) && (d == 3)) {
++counter;
}
a = b;
b = c;
c = d;
}
fclose(IN);
printf("Number of fragments: %d\n", counter);
return 0;
}
Ðåçóëüòàò âûïîëíåíèÿ:
Çàäà÷à 2. Íàéòè, ñêîëüêî ðàç â ïîñëåäîâàòåëüíîñòè
âñòðå÷àåòñÿ ôðàãìåíò:
1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 1 10
Åñëè ðåøàòü òàê æå, òî âìåñòî ñòðîêè
if ((a == 1) && (b == 2) && (c == 1) && (d == 3))
áóäåò î÷åíü äëèííîå ñðàâíåíèå.
Ïåðåìåííûå íàçûâàòü êàê, åñëè ÷èñåë áîëüøå 26?
a1, a2, a3, …, a100
Ïðèäóìàëè âìåñòî áîëüøîãî êîëè÷åñòâà îäíîòèïíûõ ïåðåìåííûõ ââîäèòü ìàññèâ (âåêòîð, òàáëèöà, …).
double a[100];
a[0], a[1], a[2], …, a[99]
(Â Ôîðòðàíå íóìåðàöèÿ ýëåìåíòîâ ìàññèâà — ñ 1, à â C – ñ íóëÿ).
a[0] = 11;
a[1] = 15;
Ïðèìåð ðàáîòû ñ ìàññèâàìè:
for (i = 0; i < 100; i++) {
a[i] = i;
}
Ñ öèêëîì while:
i = 0;
while (i < 100) {
a[i] = i;
i++;
}
Íåâåðíàÿ ðàáîòà ñ ìàññèâîì:
double a[100];
double b[100];
for (i = 0; i <= 100; i++) {
a[i] = i;
}
×òî áóäåò íà 101 øàãå? ×èñëî 100 ïðèñâîèòñÿ íå ýëåìåíòó ìàññèâà a, à ñêîðåå âñåãî b[0].
Íè êîìïèëÿòîð, íè ïðîöåññîð ïðè âûïîëíåíèè íå îòëîâÿò ýòó îøèáêó!!!
Ýòî ôè÷à (feature – äîï. âîçìîæíîñòü) ÿçûêà C.
ßçûê C – ÿçûê ñèñòåìíîãî ïðîãðàììèðîâàíèÿ.
Êàê çàíåñòè â ìàññèâ ÷èñëà 1, 2, 1, 3, 1, 4, …, 1, 10?
double array[18];
int n = 18;
-------------
array[0] = 1;
array[1] = 2;
array[2] = 1;
…
array[17] = 10;
-------------
int i;
for (i = 0; i < n; i++) {
array[i * 2] = 1;
array[i * 2 + 1] = i * 2 + 2;
}
Ðåøåíèå çàäà÷è 2:
#include <stdio.h>
int main(void) {
double array[18], fragment[18];
int counter = 0, i, equal;
FILE *IN;
IN = fopen("input.txt", "r");
if (IN == NULL) {
printf("File not opened\n");
return -1;
}
for (i = 0; i < 9; i++) {
fragment[2 * i] = 1;
fragment[2 * i + 1] = i + 2;
} /* ×èòàåì 17 ÷èñåë */
for (i = 0; i < 17; i++) {
if (fscanf(IN, "%lf", &array[i]) != 1) {
printf("Not enough numbers\n");
fclose(IN);
return -1;
}
}
while (fscanf(IN, "%lf", &array[17]) == 1) { /* read the 18th number, it’s index is 17 */
equal = 1;
for (i = 0; i < 18; i++) {
if (array[i] != fragment[i]) {
equal = 0;
break;
}
}
if (equal) {
++counter;
}
for (i = 0; i < 17; i++) {
array[i] = array[i+1];
}
}
fclose(IN);
printf("Number of fragments: %d\n", counter);
return 0;
}
Ðàáîòà ïðîãðàììû: