This repository was archived by the owner on Dec 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathconvoluted.c
More file actions
55 lines (39 loc) · 2.09 KB
/
convoluted.c
File metadata and controls
55 lines (39 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <stdio.h>
#include <cs50.h>
int main(void)
{
// Example 1 ---------------------------------------------------------------
// this works, but is a very bad idea
printf("What is the year of your birth? ");
string birthyear_str = GetString();
// this code is impossible to read because there is too much stuff crammed onto one line:
printf("In the year %i, you were halfway towards becoming who you are today!\n", atoi(birthyear_str) + (2016 - atoi(birthyear_str)) / 2);
// -------------------------------------------------------------------------
// Example 2. ---------------------------------------------------------------
// this is ever so slightly better
printf("What is the year of your birth? ");
birthyear_str = GetString();
int answer = atoi(birthyear_str) + (2016 - atoi(birthyear_str)) / 2;
printf("In the year %i, you were halfway towards becoming who you are today!\n", answer);
// but still needs to be expanded more, because:
// -- it's very difficult for someone else to understand what that math is doing.
// -- if we get a bug, it will be very difficult to figure out which part of our formula is broken
// -- we repeat the same expression twice: (2016 - atoi(birthyear))
// -------------------------------------------------------------------------
// Example 3 ---------------------------------------------------------------
// The following is much clearer.
// We break up the convulted math into multiple lines with descriptive variable names and comments
// prompt user for their birthday
printf("What is the year of your birth? ");
// get user's answer
birthyear_str = GetString();
// convert string to int
int birthyear = atoi(birthyear_str);
// calculate year at which the user was half of their current age
int currentyear = 2016;
int age = currentyear - birthyear;
int halfage = age / 2;
int halfwayYear = birthyear + halfage;
printf("In the year %i, you were halfway towards becoming who you are today!\n", halfwayYear);
// -------------------------------------------------------------------------
}