PAT (Basic Level) Practice (中文)
1001
我特么就多写了个while(1)
就通不过了。
这个能少还是得少啊。
#include <stdio.h>
int main(){
int count,a;
scanf("%d", &a);
count = 0;
while (1){
count++;
if (a%2!=0){
a = (a*3+1)/2;
}else{
a /= 2;
}
if (a ==1){
break;
}
}
printf("%d", count);
return 0;
}
这样在最后一步,时间上是过不去的,因此必须去掉while (1)
的条件
这样写可以正确通过:
#include <stdio.h>
int main(){
int count,a;
scanf("%d", &a);
count = 0;
while (a!=1){
count++;
if (a%2!=0){
a = (a*3+1)/2;
}else{
a /= 2;
}
}
printf("%d", count);
return 0;
}
1002
这道题对于我来说最大的坑无非就在于C语言操作数组特别是字符串数组非常的不熟悉。这里总结下几个遇到坑爹的地方:
- 怎么使数字(int)转换成字符串(char *),这里使用
sprintf()
来解决这个问题。 - 便是定义那个字符串数组了,那个数组的话需要定义称为二维的数组,为
char a[][5]
这种形式的,这里的话,对数组操作不熟悉是一个最大的短板。
#include <stdio.h>
#include <string.h>
int main(){
int sum, len;
char a[100];
scanf("%s", &a);
// get the sum
len = strlen(a);
sum = 0;
for (int i=0; i<len;++i){
sum += a[i] - '0';
}
char zhongwen[][5] = {"ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu"};
// transform sum to string
char temp[5];
sprintf(temp, "%d", sum);
// printf("the sum is %s", temp);
len = strlen(temp);
int index = 0;
for (int j=0; j<len; ++j){
index = temp[j] - '0';
if (j == len-1){
printf("%s", zhongwen[index]);
}else{printf("%s ", zhongwen[index]);}
}
}
值得注意的是,这道题的要求是400ms以内,而这个程序在2ms内就已经完成了,所以这道题和上面那道要求2ms完成的不是一个侧重点。这个需要多加思索。
1004
#include <stdio.h>
#include <string.h>
typedef struct student{
char name[10];
char student_num[10];
int grade;
}student;
int main(){
// input the n student
int n;
scanf("%d", &n);
student instance[n]; // array
// input the detail
char name[10];
char student_num[10];
int grade;
for (int i=0; i<n; ++i){
scanf("%s %s %d", &name, &student_num, &grade);
strcpy(instance[i].name, name);
strcpy(instance[i].student_num, student_num);
instance[i].grade = grade;
}
// find the highest and lowest
student best = instance[0];
student worst = best;
for (int j=1; j<n; ++j){
if (instance[j].grade > best.grade){
best = instance[j];
}else if(instance[j].grade < worst.grade){
worst = instance[j];
}
}
printf("%s %s\n%s %s", best.name, best.student_num, worst.name, worst.student_num);
return 0;
}
这道题开始出现的问题在于我在对字符串赋值的时候使用了=
,然后出现了报错,因此,需要使用string.h
中的strcpy()
函数。
PAT (Advanced Level)
1001
#include <stdio.h>
#include <string.h>
int main(){
long x,y;
scanf("%d %d", &x, &y);
// already get the two input num;
long sum = x+y;
char temp[7];
sprintf(temp, "%d", sum);
int len = strlen(temp);
for (int i=0; i<len; ++i){
printf("%c", temp[i]);
if (temp[i] == '-') continue;
if ((i+1)%3==len%3 && i != len-1) printf(","); // 这段代码写的很有意思,可以多考虑一下
}
return 0;
}
网友评论