12-scanf("%*s")与printf("%*s")

在scanf里用*修饰符,是起到过滤读入的作用。比如一个有三列数值的数据,我只想得到第2列数值,可以在循环里用scanf(“%*d%d%*d”,a[i])来读入第i行的第2个数值到a[i]。 
       * 修饰符在printf中的含义完全不同。如果写成printf(“%6d”, 123),很多同学应该就不会陌生了,这是设置域宽的意思。同理,%6s也是域宽。* 修饰符正是用来更灵活的控制域宽。使用%*s,表示这里的具体域宽值由后面的实参决定,如printf(“%*s”,6, “abc”)就是把”abc”放到在域宽为6的空间中右对齐。

#include <bits/stdc++.h>
using namespace std;

int main(){
	char a[10] = "abcdefgh"; 
	char b[20];
	strcpy(b, a);
	b[4] = 0; //可以作为结束符??? 
	cout << strlen(b) << endl;
	cout << a << endl;
	cout << b << endl;
	
	int c, d;
	scanf("%d%*c%d", &c, &d);  //输入1a1会跳过a直接读入a,b 
	cout << c << " " << d << endl;
	
	printf("%*s", 10, "aa");   //与scanf中的星号作用不同,代表输出aa并且aa占用10位 
	
	return 0;
}

5.九数组分数

1,2,3...9 这九个数字组成一个分数,其值恰好为1/3,如何组法?
下面的程序实现了该功能,请填写划线部分缺失的代码。

[cpp] view plain copy
 
  1. #include <stdio.h>  
  2.   
  3. void test(int x[])  
  4. {  
  5.     int a = x[0]*1000 + x[1]*100 + x[2]*10 + x[3];  
  6.     int b = x[4]*10000 + x[5]*1000 + x[6]*100 + x[7]*10 + x[8];  
  7.       
  8.     if(a*3==b) printf("%d / %d ", a, b);  
  9. }  
  10.   
  11. void f(int x[], int k)  
  12. {  
  13.     int i,t;  
  14.     if(k>=9){  
  15.         test(x);  
  16.         return;  
  17.     }  
  18.       
  19.     for(i=k; i<9; i++){  
  20.         {t=x[k]; x[k]=x[i]; x[i]=t;}  
  21.         f(x,k+1);  
  22.         _____________________________________________ // 填空处  
  23.     }  
  24. }  
  25.       
  26. int main()  
  27. {  
  28.     int x[] = {1,2,3,4,5,6,7,8,9};  
  29.     f(x,0);   
  30.     return 0;  
  31. }  

思路:f(x,k+1)回溯之后,将交换后的结果还原,所以复制题目中代码即可。

答案:{t=x[k]; x[k]=x[i]; x[i]=t;}

  

原文地址:https://www.cnblogs.com/zhumengdexiaobai/p/8604208.html