练习4-1
#include <stdio.h>
#define MAX 100
int Strrindex(char *source, char t); //4-1
void GetLine(char *s); //get string of input
int main() {
char input[MAX];//input string;
int char_t_location;
GetLine(input);
char_t_location = Strrindex(input, '4');
printf("%d\n", char_t_location);
}
void GetLine(char *s) {
int c;
while ((c = getchar()) != EOF) {
*s = c;
s++;
}
*s = '\0';
/*
array label is not variable,but pointer is variable
*/
}
//4-1
int Strrindex(char *s, char t) {
int location = 1;
int t_location = -1;
while (*s != '\0') {
if (*s == t) t_location = location;
++location;
++s;
}
return t_location;
}
练习4-2
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#define MAX 20
void GetLine(char *s);
double Atof(char s[]);
int main(void) {
double num_output;
char string_input[MAX];
GetLine(string_input);
num_output = Atof(string_input);
printf("%6.3f\n", num_output);
return 0;
}
void GetLine(char *s) {
int c;
while ((c = getchar()) != EOF) {
*s = c;
s++;
}
*s = '\0';
/*
array label is not variable,but pointer is variable
*/
}
//4-2
double Atof(char s[]) {
double val, power;
int i, sign, index;
char index_sign = '+';
for (i = 0; isspace(s[i]); i++) {}
sign = (s[i] == '-') ? -1 : 1;
if (s[i] == '+' || s[i] == '-')
i++;
for (val = 0.0; isdigit(s[i]); i++)
val = 10.0 * val + (s[i] - '0');
if (s[i] == '.')
i++;
for (power = 1.0; isdigit(s[i]); i++) {
val = 10.0 * val + (s[i] - '0');
power *= 10.0;
}
if (s[i] == 'e' || s[i] == 'E') {
++i;
if ( !(isdigit(s[i])) ) {
index_sign = (s[i] == '-') ? '-' : '+';
++i;
}
for (index = 0; isdigit(s[i]); i++)
index = 10 * index + (s[i] - '0');
if (index_sign == '+')
return sign * val / power * pow(10.0, index);
else
return sign * val / power / pow(10.0, index);
}
return sign * val / power;
}