-
Notifications
You must be signed in to change notification settings - Fork 0
/
guesshard.c
executable file
·80 lines (65 loc) · 1.6 KB
/
guesshard.c
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
int rrange(int, int);
float to1place(float);
int main()
{
srand(time(NULL));
int guess = 1;
int num = rrange(2, 500);
float root = to1place(sqrt(num));
printf("Welcome to the guessing game!\n");
printf("In this game, you have 12 guesses to try and figure out the quare root of");
printf("a given number.\n");
printf("If you enter a square root that's correct to at least one decimal place,\n");
printf("you'll win.\n");
printf("====================================================\n");
printf("What is the square root of %i?\n", num);
do
{
float sr = 0;
do
{
printf("Please enter guess %i: ", guess);
if(scanf("%f", &sr) != EOF) break;
printf("Please enter a number.\n");
}
while(1);
float temp = to1place(sr);
if(sr < root)
{
printf("You'll have to guess higher!\n");
}
else if(sr > root)
{
printf("You'll have to guess lower!\n");
}
else if(root == sr)
{
printf("You got it!\n");
return 0;
}
guess++;
}
while(guess <= 12);
printf("You lost.\n");
}
int rrange(int a, int b)
{
int temp = rand();
while(temp < a || temp > b)
{
temp = rand();
}
return temp;
}
float to1place(float a)
{
char* temp = (char*)malloc(20);
float temp2;
sprintf(temp, "%.1f", a);
sscanf(temp, "%f", &temp2);
return temp2;
}