91
阿新 • 來源:網路 • 發佈:2021-02-19
技術標籤:C
91 date:2021.2.18

首尾交換位置
對換 n/2次
詳細程式碼如下:
#include <stdio.h>
void fun(int a[], int n)
{ int i,t;
/**********found**********/
for (i=0; i< n/2; i++) //將 a[0] 與 a[n-1]對換位置 ,需要對換 n/2次
{
t=a[i];
/**********found**********/
a[i] = a[n-1-i]; // a[1] 與 a[n-2]對換位置 ,依次類推
/**********found**********/
a[n-1-i] = t;
}
}
void main()
{ int b[9]={1,2,3,4,5,6,7,8,9}, i;
printf("\nThe original data :\n");
for (i=0; i<9; i++)
printf("%4d ", b[i]);
printf("\n");
fun(b, 9);
printf("\nThe data after invert :\n");
for (i=0; i<9; i++)
printf("%4d ", b[i]);
printf("\n");
}

各種進位制的轉換方法的掌握

詳細程式碼如下:
#include <stdio.h>
#include<string.h>
int fun( char *p )
{ int n;/**********found**********/
n= *p-'0'; //用數字字元減去字元‘0’的ASCII碼,就得到對應的數字。
p++;
while( *p!=0 ) {
/**********found**********/
n=n*8+*p-'0'; //要在一個八進位制數的最後加上一位,原來各個位上的數上升一位,只需將原數乘以8再加上個位數
p++;
}
return n;
}
void main()
{ char s[6]; int i; int n;
printf("Enter a string (Ocatal digits): "); gets(s);
if(strlen(s)>5){ printf("Error: String too longer !\n\n");exit(0); }
for(i=0; s[i]; i++)
if(s[i]<'0'||s[i]>'7')
{ printf("Error: %c not is ocatal digits!\n\n",s[i]);exit(0); }
printf("The original string: "); puts(s);
n=fun(s);
printf("\n%s is convered to integer number: %d\n\n",s,n);
}

在結構體變數中修改
strcmp()函式用於字串比較—是否相同
詳細程式碼如下:
#include <stdio.h>
#include <string.h>
#define N 16
typedef struct
{ char num[10];
int s;
} STREC;
STREC fun( STREC *a, char *b )
{
/*
analyse:
目標:
函式返回指定學號的學生資料
若沒找到指定學號 —> 結構體變數中給學號置空 ,成績置-1作為函式值返回
*/
int i;
STREC str ={"\0",-1}; //若沒找到,在結構體變數中給學號置空串,給成績置-1
for(i = 0; i<N; i++)
if(strcmp(a[i].num, b)==0) //找到指定學號的資料
str = a[i];
return str;
/* error:
int i;
for(i = 0; i<N; i++)
{
if(a[i].num == b)
return a[i];
else
{
a[i].num[i] = '0';
a[i].s = -1;
return -1;
}
}
*/
}
void main()
{ STREC s[N]={{"GA005",85},{"GA003",76},{"GA002",69},{"GA004",85},
{"GA001",91},{"GA007",72},{"GA008",64},{"GA006",87},
{"GA015",85},{"GA013",91},{"GA012",64},{"GA014",91},
{"GA011",77},{"GA017",64},{"GA018",64},{"GA016",72}};
STREC h;
char m[10];
int i;FILE *out ;
printf("The original data:\n");
for(i=0; i<N; i++)
{ if(i%4==0) printf("\n");
printf("%s %3d ",s[i].num,s[i].s);
}
printf("\n\nEnter the number: ");gets(m);
h=fun( s,m );
printf("The data : ");
printf("\n%s %4d\n",h.num,h.s);
printf("\n");
out = fopen("out.dat","w") ;
h=fun(s,"GA013");
fprintf(out,"%s %4d\n",h.num,h.s);
fclose(out);
}
