c和指針第二章編程練習代碼

1.    main.c

#include<stdio.h>
int main()
{
	int a, b, c ;
	scanf ( "%d", &a ) ;
	b = increment ( a ) ;
	c = negate ( a ) ;
	printf ( "%d  %d", b, c ) ;
	return 0 ;
 } 

        increment.c

int increment ( int n )
{
	return n + 1 ;
}

        nagate.c

int negate ( int n )
{
	return -n ;
}

需手動輸入

2.書中答案:

#include<stdio.h>
#include<stdlib.h>

int main()
{
	int ch ;
	int braces ;
	
	braces = 0 ;
	
	while ( ( ch = getchar() ) != EOF )	//逐字讀取程序 
	{
		if ( ch == '{' )		//左花括號始終是合法的 
			braces += 1 ;
		if ( ch == '}' )		//右括號只在有一個左括號與其適配時才合法 
			if ( braces == 0 )
				printf ( "Extra closing brace!\n" ) ;
			else
				braces -= 1 ;
	}
					
	if ( braces > 0 )	//驗證是否存在未適配的左括號 
		printf ( "%d unmatched opening braces(s)!\n", braces ) ;
			
	return EXIT_SUCCESS ;	
}

    自己寫的:

#include<stdio.h>
#define MAX 1000

int main()
{
	int num = 0 ;
	int i ;		//數組下標 
	char ch ;
	char c[MAX] ;	//儲存字符串	
	scanf ( "%s", c ) ;
	
	while ( ( ch = getchar() ) != EOF )	//逐字讀取 
	{
		for (i =0; c[i] != '\n'; i++ )	//逐行判斷 
		{
			if ( c[i] == '{' && num >= 0 )	//必須先有左括號 
				num++ ;
		
			if ( c[i] == '}' )
				num-- ;
		}
	}
	
	if ( num == 0 )	//驗證是否適配 
		printf ( "noproblem" ) ;
	else
		printf ( "exit") ; 

	return 0 ;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章