#include <stdio.h> #include <string.h>int main () {int t,i,num; Char a[]={' C ', ' H ', ' O ', ' N '}; Double n[]={12.01,1.008,16.00,14.01};//This so-called constant array of the magical char s[105]; Double sum; scanf ("%d", &t); while (t--) {sum=0;//sum resets scanf ("%s", s) each time multiple sets of data input are entered; For (I=0;i<strlen (s); i++) {if (s[i+1]>= ' 0 ' &&s[i+1]<= ' 9 ')//characters followed by a number { if (s[i+2]>= ' 0 ' &&s[i+2]<= ' 9 ')//with two-digit number {num=10* (s[i+1]-' 0 ') + (s[i+2]-' 0 '); } else//with a digit num=s[i+1]-' 0 '; } else//with no digital num=1; if (s[i]==a[0]) sum + = num*n[0]; else if (s[i]==a[1]) sum + = num*n[1]; else if (s[i]==a[2]) sum + = num*n[2]; else if (s[i]==a[3]) sum + = num*n[3]; } printf ("%.3f\n", sum); } return 0;}
#include <stdio.h> #include <string.h>int main () {double d[200]; int n,sum,i; Double W; Char c,a[1000]; d[' C ']=12.01; d[' H ']=1.008; d[' O ']=16.00; d[' N ']=14.01; The magical scanf of a constant Array ("%d", &n); while (n--) {i=0; w=0; scanf ("%s", a); while (a[i]!= ') {sum=0; C=a[i]; i++; while (a[i]>= ' 0 ' && a[i]<= ' 9 ')//determine how many digits after the character {sum=sum*10+a[i]-' 0 '; Sum is a numeric size/includes a number occupying the back 1,2,3 Bit of i++; Traverse backward If there is a number} if (sum)//If the character is followed by a number, molecular weight = molecular number * Unit atomic mass w+=sum* (D[c]); else//If the character is followed by countless characters w+= (D[c]); } printf ("%.3f\n", W); } return 0;} /* Problem Solving ideas: 1. The molecular weight is recorded in a double array 2. Store the string in a character array, scan from the back, remember the word "letter", judge the next character, whether it is a number, if it is a number: Record with an integer, sum in this code, and subscript + +. To determine whether the number is recorded, that is to see if the sum has entered the while loop and is assigned, if not assigned, the next character is not a number, the W (total record) value is directly assigned to the currentThe weight of the character (the molecular weight), which is the value in the double array. If the value is assigned, the description character is followed by a number, the sum holds the number, and the W is assigned, but at this time the weight (molecular weight) of the current character that is assigned sum. 3. Finally the entire string loop is complete, the output total record W can be. */
Purple Book Exercise 3-2 molecular weight (string, constant array)