[C Programming Tutorial Experiment] Basic Exercises (7)

code one

//运行下列程序的输出结果是? 
#include  <stdio.h>
int main()
{
    
    
	int x=1,y,z;
	
	x*=3+2;	printf("%d\t",x); // x=1*3+2=5
	x*=y=z=5;	printf("%d\t",x);	// x=5*5=25, y=z=5
	x=y==z;	printf("%d\n",x);	// 由于 y==z正确,即取1,故 x=1 
	
	return 0;	
	 	
}

The output is as follows:
--------------- Look at the comments!
insert image description here

code two

//下列表达式输出的值为? 
#include <stdio.h>
int main()
{
    
    
	int a;
	int w=1,x=2,y=3,z=4;
	a=w<x?w:y<z?y:z;
	//可以 加上括号 理解上述语句  (w<x)?(w):(y<z?y:z)
	printf("a=%d\n",a); // a=1
	
	return 0; 
}

The output is:

This result is similar to a question I uploaded before. The main thing is to understand the (?:) expression well.
insert image description here
You can modify the above program:

//测试 
//下列表达式输出的值为? 
#include <stdio.h>
int main()
{
    
    
	int a;
	int w=5,x=2,y=3,z=4;   //将w改为5,进而使得w<x不满足。 
	a=w<x?w:y<z?y:z;
	//可以 加上括号 理解上述语句  (w<x)?(w):(y<z?y:z)
	printf("a=%d\n",a); // a=3
	
	return 0; 
}

Therefore, the statement executed at this time is the statement after the colon ":", and then it is judged that y<z is satisfied, so y is executed, that is, a=y=3.
insert image description here

Code 3: Program fill in the blanks

//计算1+3+5+7+9+...+99+101的值,程序填空
#include <stdio.h>
int main()
{
    
    
	int i,sum=0;
	for(i=1;i<=101; i+=2){
    
     //程序填空  i+=2
		sum+=i; //程序填空	sum+=i	
	}
	printf("sum=%d\n",sum); 
 } 

insert image description here

Code 4: The program fills in the blanks (a little error-prone, read the question!)

//程序填空
// 计算 a + aa + aaa +...+aa..a(n个a)的值
// 其中n和a的值由键盘输入

#include <stdio.h>
int main()
{
    
    
	long term = 0; //程序填空 term = 0  
	int sum = 0;
	int a,i,n;
	printf("Input a,n:");
	scanf("%d,%d",&a,&n); //例如:a=2,n=3,则求 2 + 22 + 222 的值 
	for(i=1;i<=n;i++) 
	{
    
    
		term =  term*10 + a; //程序填空  term*10 + a
		sum = sum + term;
		 
	}
	printf("sum=%ld\n",sum);
 } 

test:

insert image description here
insert image description here
Let's eat~

Guess you like

Origin blog.csdn.net/qq_44731019/article/details/123680529