【程序一】不同进制数的输出

#include<iostream>

using namespace std;

int main()
{
	int num;
	cout << "请输入一个整型数:";
	cin >> num;
	cout << "八进制数是:" << oct << num << endl;
	cout << "十进制数是:" << dec << num << endl;
	cout << "十六进制数是:" << hex << num << endl;
	return 0;
}

 【程序二】get函数和getline函数

#include<iostream>

using namespace std;

int main()
{
	char s1, s2, s3[50], s4[50];
	cout << "请输入一个字符:";
	cout << cin.get() << endl;//读取一个字符的ASCII码值
	cin.get();//提取换行符
	cout << "请输入两个字符:";
	cin.get(s1).get(s2);
	cout << s1 << s2 << endl;
	cin.get();
	cout << "请输入一个字符串:";
	cin.get(s3, 50);
	cout << s3 << endl;
	cin.get();
	cout << "请输入一个字符串:";
	cin.getline(s4, 50);
	cout << s4 << endl;
	return 0;
}

 【程序三】read函数

#include<iostream>

using namespace std;

int main()
{
	char ch[100];
	char* str = ch;
	cout << "read 函数的使用:" << endl;
	cout << "请输入字符:" << endl;
	cin.read(str, 100);
	str[cin.gcount()] = '\0';//这一句要有,否则会出现乱码 
	cout << str << endl;
}

 【程序四】put函数和write函数应用

#include<iostream>
#include<string.h>

using namespace std;

int main()
{
	char s1[100], s2[50] = "Happy new year";
	cout << "put 和 writer函数的应用!" << endl;
	cout << 'M' << endl;
	cout.put('M');
	cout.put('\n');
	cout << "请输入一串字符:";
	cin.read(s1, 100);
	cout.write(s1, 5) << endl;
	cout.write(s2, strlen(s2)) << endl;
	return 0;
}

 【程序五】生产随机数

1、rand()函数

该函数是一个随机发生器,返回一个随机数值,范围在[0, RAND_MAX]之间。RAND_MAX定义在stdlib.h头文件中,C++中可以使用cstdlib头文件。

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    cout << "RAND_MAX:" << RAND_MAX << endl;
    for (int i = 0; i < 5; i++)
        cout << rand() << endl;
}

2、srand()函数

为了避免每次生成固定的随机数,引进srand()函数。该函数的功能是初始化随机数发生器,同样在头文件cstdlib中。

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

int main()
{
    cout << "RAND_MAX:" << RAND_MAX << endl;
    srand((unsigned)time(NULL));
    for (int i = 0; i < 5; i++)
        cout << rand() << endl;
}

 3、产生指定范围内的随机数
要产生指定范围内的随机数,可以先使用rand()函数产生一个[0,RAND_MAX]范围内的随机数,然后在变换到指定范围内。
产生[a,b)的随机数,可以使用 (rand() % (b-a))+a;
产生[a,b]的随机数,可以使用 (rand() % (b-a+1))+a;
产生(a,b]的随机数,可以使用 (rand() % (b-a))+a+1;
通用公式:a+rand() % n;
其中:a为范围起始位置,n为整数的范围
产生[a,b]的随机数,可以使用 a+(int)b*rand()/(RAND_MAX+1);
产生[0,1]的浮点数,可以使用 rand()/double(RAND_MAX);
 

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

int main()
{
    cout << "RAND_MAX:" << RAND_MAX << endl;
    srand((unsigned)time(NULL));
    for (int i = 0; i < 5; i++)
        cout << (rand() % 2) << " ";         //生成[0,1]范围内的随机数
    cout << endl;
    for (int i = 0; i < 5; i++)
        cout << (rand() % 5 + 3) << " "; //生成[3,7]范围内的随机数
    cout << endl;
}

码字不易!都看到这啦 可以给我点赞收藏支持一下 万分感谢

今天就分享到这!!后面会持续更新C/C++的相关知识~大家可以关注一波

如果有学习上的问题或者想要更多学习资料,项目源码,视频教学可以点击我的主页,进群,欢迎大家积极讨论!!!

群主是我自己啦! 欢迎大家进群交流!

点击即可进群http://点击链接加入群聊【C语言C++交流学习群】:https://jq.qq/?_wv=1027&k=E2jTlQ6k

更多推荐

五个C++必须要掌握的程序,附代码