首页
网站开发
桌面应用
管理软件
微信开发
App开发
嵌入式软件
工具软件
数据采集与分析
其他
首页
>
> 详细
Structures编程辅导、讲解c/c++程序语言、辅导program程序 解析Java程序|讲解R语言程序
项目预算:
开发周期:
发布时间:
要求地区:
UoG-UESTC 2020 Page 1 of 9
Lab Session: Strings, Structures and Bit Manipulation
Exercise 1: Strings are Arrays of Characters
Background
You may recall that in Lab 1, we defined strings variables as:
char animal[100] = "cat";
As you may guess now, we were actually creating an array of characters.
You may have noticed that we can print out a string without needing to specify the total
number of characters:
char animal[100] = "ferocious kitten";
printf("The %s sleeps!", animal);
The above code will print out "The ferocious kitten sleeps", even though the
char array animal contains 100 chars. This is because the final character is a special
ascii-null character: '\0' (added automatically by the compiler in this case)
Technical details
Dealing with strings:
#include
#include
// extra include!
int main() {
char animal[100] = "ferocious kitten";
// length of the string
int length = strlen(animal);
int i;
for (i=0; i
printf("%c", animal[i]);
}
printf("\n");
getchar();
return 0;
}
We can also copy strings.
#include
#include
int main () {
char orig[100]= "Cats are awesome";
char next[100];
UoG-UESTC 2020 Page 2 of 9
// 99 is the maximum number of chars
strncpy(next,orig,99);
printf("%s\n", next);
getchar();
return 0;
}
Your task...
The Coleman-Liau Index test[1] is an easily-computable estimation of the difficulty of
reading some text. It gives an approximate "grade level" (in US school system: grade 1 is
for students 5-6 years old, and the numbers increase linearly until grade 12).
𝐶𝐿𝐼 = 5.89 (
characters
words ) − 29.5 (
sentences
words ) − 15.8
In the above formula, "character" means "letter" -- for the purposes of that formula, spaces
and periods do not count as characters.
[1] Coleman, M.; and Liau, T. L. (1975); A computer readability formula designed
for machine scoring, Journal of Applied Psychology, Vol. 60, pp. 283-284.
Original journal paper (campus access only)
Write a program that calculates the Coleman-Liau Index of some text.
• Perform the actual calculation in a function which accepts char text[] as input
and returns the Coleman-Liau grade level.
• If the calculated grade is less than 1, set it to 1 instead of returning a lower
number.
• You may assume that the text:
o begins with a word
o ends with a period
o contains no numbers or non-letters
o there is one space between words, and one space after a period (other
than the final period).
o each sentence ends with a period; no exclaimation marks or question
marks are used.
(hint: what is the relationship between the number of periods, number of spaces,
and the words+sentences in the text?)
(another hint: how can you count the number of periods and spaces in the text?)
• Test it with the following three exerpts. For these definitions, you may ignore the
code style requirement that lines should be less than 80 characters long. When
you cut&paste this into your .c file, you might need to ensure that it all goes onto
one line.
UoG-UESTC 2020 Page 3 of 9
1. char text[100] = "I like cats. Cats like me. Miao miao
miao. Dogs are bad. Bad dogs bad.";
(words of wisdom)
(hint: the above fragment has 70 characters, 51 letters, 15 words, 14
spaces, 5 periods, 5 sentences, and a calculated CLI of -5.6, which we
change to be grade 1.)
2. char text[500] = "Tomorrow, and tomorrow, and
tomorrow, Creeps in this petty pace from day to day,
To the last syllable of recorded time; And all our
yesterdays have lighted fools The way to dusty death.
Out, out, brief candle. Life's but a walking shadow,
a poor player That struts and frets his hour upon the
stage And then is heard no more. It is a tale Told by
an idiot, full of sound and fury Signifying nothing."
(Macbeth: Act 5, Scene 5, lines 19-28)
3. char text[1000] = "Existing computer programs that
measure readability are based largely upon subroutines
which estimate number of syllables, usually by
counting vowels. The shortcoming in estimating
syllables is that it necessitates keypunching the
prose into the computer. There is no need to estimate
syllables since word length in letters is a better
predictor of readability than word length in
syllables. Therefore, a new readability formula was
computed that has for its predictors letters per
hundred words and sentences per hundred words. Both
predictors can be counted by an optical scanning
device, and thus the formula makes it economically
feasible for an organization such as the US Office of
Education to calibrate the readability of all
textbooks for the public school system."
(abstract of Coleman-Liau journal paper.)
(optional: research and implement the Automated Readibility Index (ARI). Compare
those results with the Coleman-Liau results.)
Note: Show your work to a demonstrator/GTA.
Exercise 2: Combining variables with struct
Background
You may have noticed that functions can only return one variable. But what if want to
return more information than we can hold in one variable? The answer is to pack multiple
variables together into a single structure.
This creates a new type of variable which contains a number of fields. In this section's
example, we create a new type of variable called struct SquareData. We can declare
UoG-UESTC 2020 Page 4 of 9
this just like other variables -- instead of writing int or float, we write
struct SquareData.
After we have declared a variable of this type with:
struct SquareData mySquare;
we can access its fields with mySquare.side, mySquare.area or any other field
name after the period.
Returning a struct is a modern addition to the language. It was not supported in the
original C standard in 1972, but was added in the ANSI C standard (also sometimes known
as "C89" or "C90"). Some very old compilers might not support ANSI C. We will see
another way to return multiple values in a few weeks.
Technical details
Structure:
#include
struct SquareData {
float area;
float perimeter;
int side;
};
struct SquareData calcSquare(int x) {
//define variable of data type structure
struct SquareData mySquare;
mySquare.side = x;
mySquare.perimeter = 4*x;
mySquare.area = x*x;
// we need to return this to main()
return mySquare;
}
void printStuff(struct SquareData mySquare) {
// this is not useful here, but it works
float areaBAD = mySquare.area;
printf("The square's sides are ");
printf("%i units long, ", mySquare.side);
printf("and thus has \nan area of ");
printf("%f units, and ", areaBAD);
printf("a perimeter of ");
printf("%f units.\n", mySquare.perimeter);
}
int main() {
UoG-UESTC 2020 Page 5 of 9
struct SquareData square;
square = calcSquare(2);
printStuff(square);
getchar();
return 0;
}
The syntax of a struct is a bit confusing. Make sure that you follow the example
carefully when you use them. Be particularly careful about the final semicolon “;“after
the struct definition's final ”}”, and about adding struct in front of the structure's
name.
Here's another example of struct:
#include
struct TimeData {
int total_minutes;
int hours;
int minutes;
};
struct TimeData calcTime(int day_minutes) {
struct TimeData time;
time.total_minutes = day_minutes;
time.hours = day_minutes / 60;
time.minutes = day_minutes % 60;
return time;
}
void printTime(struct TimeData myTime) {
printf("It has been ");
printf("%i", myTime.total_minutes);
printf(" minutes since midnight.\n");
printf("The time is therefore ");
printf("%02i:", myTime.hours);
printf("%02i ", myTime.minutes);
printf("o'clock.\n");
}
int main() {
struct TimeData time;
time = calcTime(123);
printTime(time);
time = calcTime(1234);
printTime(time);
getchar();
return 0;
UoG-UESTC 2020 Page 6 of 9
}
Your task...
Vending machines use simple programs to calculate the amount of change to return. For
a machine, the coins are dispensed mechanically. In our program, we will output the
numbers to the screen, looking something like this:
Customer gave 10 pence, item(s) cost 7 pence.
Give customer:
£2 £1 50 20 10 5 2 1
0 0 0 0 0 0 1 1
Customer gave 70 pence, item(s) cost 56 pence.
Give customer:
£2 £1 50 20 10 5 2 1
0 0 0 0 1 0 2 0
Customer gave 200 pence, item(s) cost 124 pence.
Give customer:
£2 £1 50 20 10 5 2 1
0 0 1 1 0 1 0 1
Customer gave 2000 pence, item(s) cost 1232 pence.
Give customer:
£2 £1 50 20 10 5 2 1
3 1 1 0 1 1 1 1
Write a program that calculates the amount of coins to return.
Before you begin, figure out the math on paper. Show your formula(s) to a lab
demonstrator before you start programming.
• Your int main() loop must be this:
int main() {
struct Change coins;
coins = getChange(7, 10);
printChange(coins);
coins = getChange(56, 70);
printChange(coins);
coins = getChange(124, 200);
printChange(coins);
coins = getChange(1232, 2000);
printChange(coins);
getchar();
return 0;
}
Remember that C is case-sensitive. As far as the computer is concerned, UPPERCASE
letters are completely different from lower-case letters!
• You must write the getChange(...) and printChange(...) functions, and
the definition of struct Change. The first function must do all the math; the
second function must do all the printf(...). Use the struct Change to pass
information between these functions.
UoG-UESTC 2020 Page 7 of 9
• Britain has the following coins: 1 pence, 2 pence, 5 pence, 10 pence, 20 pence, 50
pence, 1 pound (100 pence), and 2 pounds (200 pence). Your machine should not
dispense any bills.
• You may assume that your vending machine has an infinite amount of coins, but
you should always dispense the largest coins first.
• You do not need to print the pound £ symbol. You may output 200 instead of £2.
• Your program should use int for all variables, and keep track of the number of
pence instead of pounds.
You should never keep track of money with float.
Can you guess why?
(optional: try using float (storing pounds, not pence) to program your vending machine.
Can you make it give accurate results?)
Note: Show your work to a demonstrator/GTA.
Exercise 3: Bit manipulation
Background
As engineers, you will (or should at least!) have more interest in bitwise manipulation
than most other programmers. Writing software that controls lights, reacts to flipped
switches, and generally anything that interacts closely with hardware will require bitwise
operations. The main concepts here are flags and bitmasks (commonly known as "masks).
A flag is a particular bit with a special meaning. For example, when representing negative
numbers, the 8th bit could be thought of a flag which indicated whether the remainder of
the bits should be interpreted as a positive or negative number.
A bitmask is a way of accessing a particular bit (generally, but not always, a flag). The
bitmask is a number which has 0 in all bits we don't care about, and a 1 for the bit(s) that
we want to examine. By anding the bitmask with the original number, we can "extract"
the bit(s) -- if that bit was 0, then the new number will be completely zero; if the bit was 1,
then the new number will be non-zero.
The same operation is done in reverse to set a flag -- by oring a bitmask and the data
variable, we can set a flag to be true. Setting a flag can be done by anding the variable with
the noted bitmask.
Technical details
Various bitwise operations:
#include
int main() {
char x = 0x10; // number in hex
char y = 63;
printf("char is a one-byte number. ");
UoG-UESTC 2020 Page 8 of 9
printf("Printing it with %%c will treat ");
printf("it as\nan ASCII value, but we ");
printf("can also print it as a number: ");
printf("x=%i y=%i.\n", x, y);
printf("Some operations: ");
printf("%i\t%i\n", ~x, ~y);
printf("%i\t%i\t%i\n", x&y, x|y, x^y);
getchar();
return 0;
}
Toggling individual bits:
#include
#include
// extra includes!
#include
float getRand() {
return rand() / (RAND_MAX+1.0);
}
int main() {
srand( time(NULL) ); // init random
char x = 0;
char bit, bitmask;
int i;
// Building a bitwise random number
for (i=0; i<8; i++) {
// set bit as 1 or 0?
if (getRand() > 0.5) {
bit = 1;
} else {
bit = 0;
}
// get bit ready
bitmask = bit << i;
// or them together
x = x | bitmask;
printf("After round %i, ",i);
printf("bit is %i, and ", bit);
printf("x is %i.\n", x);
}
getchar();
return 0;
}
Your task...
UoG-UESTC 2020 Page 9 of 9
Dougie Dog has invented an "encryption" technique to keep secrets from the Ferocious
Kittens. Fortunately, cats are extremely intelligent, and have cracked the simple code:
1. Letters are grouped into pairs. Add a space to the end of the string if necessary to
give it an even number of characters (here "character" means char.
2. Make an int from each pair by sticking the bits from the first letter in front of the
bits from the second letter. You may assume that we are using 8-bit ASCII.
3. XOR the result with 31337.
Here's two examples of encryption: "cats" and "kittens".
1. Pairs: "ca ts"
"ki tt en s_" (_ represents a space)
2. into ints: 25441 29811
27497 29812 25966 29472
3. XOR with 31337: 6408 3610
4352 3613 7943 2377
Decryption is performed with the same steps, but in reverse order.
• The Ferocious Kittens have intercepted two secret messages from Dougie Dog:
15643 6913 6916 23040 2377 6985 6408 3657 5638 3084 2119
15910 23079 13629 23101 10300 10557 23073 13092 23369
• Write a program that decrypts them.
(hint: this will be a lot easier if you begin by writing a program to encrypt values -
- you can check each step with "cats" and "kittens" to make sure you understand
the process!)
• You must use a function to split a large integer into two separate letters. This
function may not print anything to the screen.
(hint: how can a function return two values?)
Note: Show your work to a demonstrator/GTA.
软件开发、广告设计客服
QQ:99515681
邮箱:99515681@qq.com
工作时间:8:00-23:00
微信:codinghelp
热点项目
更多
代做ceng0013 design of a pro...
2024-11-13
代做mech4880 refrigeration a...
2024-11-13
代做mcd1350: media studies a...
2024-11-13
代写fint b338f (autumn 2024)...
2024-11-13
代做engd3000 design of tunab...
2024-11-13
代做n1611 financial economet...
2024-11-13
代做econ 2331: economic and ...
2024-11-13
代做cs770/870 assignment 8代...
2024-11-13
代写amath 481/581 autumn qua...
2024-11-13
代做ccc8013 the process of s...
2024-11-13
代写csit040 – modern comput...
2024-11-13
代写econ 2070: introduc2on t...
2024-11-13
代写cct260, project 2 person...
2024-11-13
热点标签
mktg2509
csci 2600
38170
lng302
csse3010
phas3226
77938
arch1162
engn4536/engn6536
acx5903
comp151101
phl245
cse12
comp9312
stat3016/6016
phas0038
comp2140
6qqmb312
xjco3011
rest0005
ematm0051
5qqmn219
lubs5062m
eee8155
cege0100
eap033
artd1109
mat246
etc3430
ecmm462
mis102
inft6800
ddes9903
comp6521
comp9517
comp3331/9331
comp4337
comp6008
comp9414
bu.231.790.81
man00150m
csb352h
math1041
eengm4100
isys1002
08
6057cem
mktg3504
mthm036
mtrx1701
mth3241
eeee3086
cmp-7038b
cmp-7000a
ints4010
econ2151
infs5710
fins5516
fin3309
fins5510
gsoe9340
math2007
math2036
soee5010
mark3088
infs3605
elec9714
comp2271
ma214
comp2211
infs3604
600426
sit254
acct3091
bbt405
msin0116
com107/com113
mark5826
sit120
comp9021
eco2101
eeen40700
cs253
ece3114
ecmm447
chns3000
math377
itd102
comp9444
comp(2041|9044)
econ0060
econ7230
mgt001371
ecs-323
cs6250
mgdi60012
mdia2012
comm221001
comm5000
ma1008
engl642
econ241
com333
math367
mis201
nbs-7041x
meek16104
econ2003
comm1190
mbas902
comp-1027
dpst1091
comp7315
eppd1033
m06
ee3025
msci231
bb113/bbs1063
fc709
comp3425
comp9417
econ42915
cb9101
math1102e
chme0017
fc307
mkt60104
5522usst
litr1-uc6201.200
ee1102
cosc2803
math39512
omp9727
int2067/int5051
bsb151
mgt253
fc021
babs2202
mis2002s
phya21
18-213
cege0012
mdia1002
math38032
mech5125
07
cisc102
mgx3110
cs240
11175
fin3020s
eco3420
ictten622
comp9727
cpt111
de114102d
mgm320h5s
bafi1019
math21112
efim20036
mn-3503
fins5568
110.807
bcpm000028
info6030
bma0092
bcpm0054
math20212
ce335
cs365
cenv6141
ftec5580
math2010
ec3450
comm1170
ecmt1010
csci-ua.0480-003
econ12-200
ib3960
ectb60h3f
cs247—assignment
tk3163
ics3u
ib3j80
comp20008
comp9334
eppd1063
acct2343
cct109
isys1055/3412
math350-real
math2014
eec180
stat141b
econ2101
msinm014/msing014/msing014b
fit2004
comp643
bu1002
cm2030
联系我们
- QQ: 9951568
© 2021
www.rj363.com
软件定制开发网!