1、不使用printf,将十进制数以二进制和十六进制的形式输出
解析:用字符串表示十进制数。如果不适用printf系列函数,我们可以通过位运算得到十进制数的二进制和和十六进制形式的字符串,再将字符串打印。
#include <stdio.h>#include <stdlib.h>#include <string.h>//得到二进制字符串char *get2String(long num){ int i=0; char* buffer; char* temp; buffer = (char*)malloc(33); temp = buffer; for(i=0; i < 32; i++) { temp[i] = num & (1 << (31 - i)); temp[i] = temp[i] >> (31 - i); temp[i] = (temp[i] == 0) ? '0': '1'; } buffer[32] = '\0'; return buffer;}//得到十六进制字符串char *get16String(long num){ int i=0; char* buffer = (char*)malloc(11); char* temp; buffer[0] = '0'; //以0x为开头 buffer[1] = 'x'; buffer[10] = '\0'; temp = buffer + 2; for(i=0; i < 8; i++) { temp[i] = (char)(num<<4 * i>>28); temp[i] = temp[i] >= 0 ? temp[i] : temp[i] + 15; temp[i] = temp[i] < 10 ? temp[i] + 48 :temp[i] + 56; } return buffer;}void main(){ char *p = NULL; char *q = NULL; int num = 0; printf("input num: "); scanf("%d", &num); p = get16String(num); q = get2String(num); printf("%s\n", p); printf("%s\n", q); return 0; }2、编程实现转换字符串、插入字符的个数
解析:需要统计字符串插入字符的个数,我的想法通过长度来判断插入字符的个数。
#include <iostream>#include <string>using namespace std;void main(){ char str = "aaa";}三 、泛型编程
函数模板代表同构造函数,重点在函数,类型不需要特别指定,实现复用。类模板是一种更高层次的抽象结构的类定义。函数模板的实例化是在处理函数调用时自动完成,而类模板的实例化必须由程序员中显示指定。
模板的缺点: 不当地使用模板导致膨胀,即二进制码臃肿而松散,会严重影响程序运行效率。
解决方法: 把C++模板中参数无关的代码分离出来。
例子:
template <class T, int num>class A{public: void work() { cout << "work()" << endl; cout << num << endl; }};int main(){ A<int, 1>v1; A<int, 2>v2; A<int, 3>v3; A<int, 4>v4; v1.work(); v2.work(); v3.work(); v4.work(); return 0; }改进:
template <class T>class base{public: void work(int num) { cout << " work "; cout << num << endl; }};template<class T,int num>
class Derived : public base<T> {public: void work() { base <T>::work(num); }};int main(){ Derived<int, 1>d1; Derived<int, 2>d2; Derived<int, 3>d3; d1.work(); d2.work(); d3.work(); return 0; }
3057

被折叠的 条评论
为什么被折叠?



