第三章习题

it2024-11-27  12

1 #include<stdio.h> 2 //Score 3 int main() 4 { 5 6 int tot = 0; 7 int all = 0; 8 int c; 9 10 while((c=getchar())!='\n') 11 { 12 if(c=='O') 13 { 14 tot++; 15 all+=tot; 16 } 17 else 18 { 19 tot=0; 20 all+=tot; 21 } 22 } 23 24 printf("%d\n", all); 25 }

 

 

3-2 Molar_Mass

刚开始纠结于不用数组,结果各种程序漏洞,改成用数组后不仅逻辑更加清晰也更好写了

1 #include<cstdio> 2 #include<ctype.h> 3 #include<cstring> 4 5 #define maxn 100 6 char arr[maxn]; 7 8 int main() 9 { 10 double ato_ma=0.0; 11 double mo_ma=0.0; 12 13 scanf("%s",arr); 14 15 int n=strlen(arr); 16 17 for(int i=0;i<n;i++) 18 { 19 switch (arr[i]) 20 { 21 case 'C': ato_ma=12.01; 22 break; 23 case 'H': ato_ma=1.008; 24 break; 25 case 'O': ato_ma=16.00; 26 break; 27 case 'N': ato_ma=14.01; 28 } 29 30 if(isalpha(arr[i]) && i+1<n) 31 { 32 if(isdigit(arr[i+1])) 33 mo_ma+=ato_ma*(arr[i+1]-'0'); 34 else 35 mo_ma+=ato_ma; 36 } 37 38 if(isalpha(arr[i]) && i+1==n) 39 mo_ma+=ato_ma; 40 } 41 42 printf("%.3lfg/mol\n",mo_ma); 43 }

 

3-3 Digit Counting

用sprintf可以写出很简介的代码           这里有篇关于sprintf用法的文章,感觉很有用

1 #include<cstdio> 2 3 #define maxn 10 4 char num[maxn]; 5 6 int main() 7 { 8 9 int max_n; 10 scanf("%d",&max_n); 11 12 int count_1=0; 13 int count_2=0; //最近写汇编写多了:) 14 int count_3=0; 15 int count_4=0; 16 int count_5=0; 17 int count_6=0; 18 int count_7=0; 19 int count_8=0; 20 int count_9=0; 21 int count_0=0; 22 23 for(int i=1;i<=max_n;i++) 24 { 25 //把数字变成字符串存在数组中 26 int n=sprintf(num,"%d",i); 27 //printf("%d\n",n); 28 29 //统计数组中出现的字符 30 for(int j=0;j<n;j++) 31 { 32 switch (num[j]) 33 { 34 case '0': 35 count_0++; 36 break; 37 case '1': 38 count_1++; 39 break; 40 case '2': 41 count_2++; 42 break; 43 case '3': 44 count_3++; 45 break; 46 case '4': 47 count_4++; 48 break; 49 case '5': 50 count_5++; 51 break; 52 case '6': 53 count_6++; 54 break; 55 case '7': 56 count_7++; 57 break; 58 case '8': 59 count_8++; 60 break; 61 case '9': 62 count_9++; 63 } 64 } 65 } 66 67 printf("%d %d %d %d %d %d %d %d %d %d\n",count_0,count_1,count_2,count_3, 68 count_4,count_5,count_6,count_7,count_8,count_9); 69 }

 

转载于:https://www.cnblogs.com/tclan126/p/7161525.html

相关资源:DirectX修复工具V4.0增强版
最新回复(0)