Вы находитесь на странице: 1из 10

Задания к самостоятельной работе

1. Записать в двумерный массив размера 8Х8 случайные


вещественные числа, значения которых от 0 до 100. Вывести полученный
массив на экран и записать в файл в виде выровненной матрицы с двумя
знаками после запятой.
#include <iostream>
#include <fstream>
#include <ctime>
#include <stdlib.h>
#include <iomanip>

using namespace std;

int main(){
ifstream in;
ofstream out;
out.open("C:\\Users\\Бекжан\\Desktop\\Бекжан\\answers.txt");
srand(time(NULL));
double a[8][8];
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
a[i][j] = (rand()%200)/(double)(rand()%100+2);
}
}
for(int i=0;i<8;i++){
for(int j=0;j<8;j++){
cout≪a[i][j]≪" ";
out<<setw(7)<<setprecision(2)<<setiosflags(ios::fixed)<<a[i][j];
}
cout≪endl;
out<<endl;
}
out.close();
}
2. В файле есть сведения об автомобилях: марка автомобиля, номер и
фамилия владельца.
а) Вывести сведения о владельцах и номерах автомобилей каждой
марки автомобиля.
б) Подсчитать количество автомобилей каждой марки.
#include <iostream>
#include <fstream>

using namespace std;

struct autom{
char name[20],number[6],sname[20];
};

int main(){
ifstream in;
in.open("C:\\Users\\Бекжан\\Desktop\\Бекжан\\automobiles.txt");
if(!in.is_open()){
cout<<"File doesn't exist"<<endl;
}
else{
cout<<"File have been opened"<<endl;
int cnt1=0,cnt2=0,cnt3=0,cnt4=0,n;
in>>n;
autom a[n];
for(int i=0;i<n;i++){
in>>a[i].name>>a[i].number>>a[i].sname;
}
string m = "Mersedez",b="BMW",h="Honda",t = "Toyota";
for(int i=0;i<n;i++){
cout<<a[i].name<<": "<<a[i].sname<<", number:
"<<a[i].number<<endl;
if(a[i].name==m){
cnt1++;
}
if(a[i].name==b){
cnt2++;
}
if(a[i].name==h){
cnt3++;
}
if(a[i].name==t){
cnt4++;
}
}
in.close();

cout<<"Mersedez amount: "<<cnt1<<endl;


cout<<"BMW amount: "<<cnt2<<endl;
cout<<"Honda amount: "<<cnt3<<endl;
cout<<"Toyota amount: "<<cnt4<<endl;

}
}

3. Текст записан одной длинной строкой. Признаком красной строки


служит символ $. Переформатировать текст в 60-символьные строки,
формируя абзацы. Исходный текст должен быть взят из файла, название
которого будет введено с клавиатуры, а результирующий текст должен быть
выведен в файл «Result_file.txt».
#include <iostream>
#include <fstream>
using namespace std;

int main(){

ifstream in;
ofstream out;
char path[50];
cout<<"Enter name of your file(with extension)"<<endl;
cin>>path;
in.open(path);
out.open("result.txt");
char a;
int cnt = 0;
if(!in.is_open()){
cout<<"File doesn't exist"<<endl;
}
else{

cout<<"Converted, check your file"<<endl;

while(!in.eof()){
in>>noskipws>>a;
cnt++;
if(cnt==60){
cnt=0;
out<<endl;
}

if(a=='$'){
out<<endl;
}
out<<a;
}
}
in.close();
out.close();

}
4. Текст, не содержащий собственных имён и сокращений, набран
полностью прописными буквами. Заменить все прописные буквы, кроме
букв, стоящих после точки, строчными буквами. Исходный текст должен
быть взят из файла, название которого будет введено с клавиатуры, а
результирующий текст должен быть выведен в файл «Result_file.txt».
#include <iostream>
#include <fstream>

using namespace std;

int main(){

ifstream in;
ofstream out;
char path[50];
cout<<"Enter name of your file(with extension)"<<endl;
cin>>path;
in.open(path);
out.open("result.txt");
char a;
int cnt = 0;
if(!in.is_open()){
cout<<"File doesn't exist"<<endl;
}
else{

cout<<"Converted, check your file"<<endl;


while(!in.eof()){
in>>noskipws>>a;
if(a=='.'){
cnt++;
out<<a;
continue;
}
if(isspace(a)){
out<<a;
}
if(cnt==1&&!isspace(a)){
a = toupper(a);
out<<a;
cnt = 0;
continue;
}
if(isupper(a)){
a = tolower(a);
out<<a;
}
}

}
in.close();
out.close();
}

5. За стоянку до трех часов парковочный гараж запрашивает плату


минимум $2.00. В случае стоянки более трех часов гараж дополнительно
запрашивает $0.50 за каждый полный или неполный час сверх трех
часов. Максимальная плата за сутки составляет $10.00. Допустим, что
никто не паркуется более, чем на сутки за раз. Напишите программу
расчета и печати оплаты за парковку для каждого из трех
клиентов, которые парковали свои автомобили вчера в этом гараже. Вы
должны вводить длительность парковки для каждого клиента. Ваша
программа должна печатать результаты в аккуратном табулированном
формате и должна рассчитывать и печатать общий вчерашний доход.
Программа должна использовать функцию calculateCharges, чтобы оп-
ределять плату для каждого клиента. Результаты работы должны пред-
ставляться в следующем формате:
Автомобиль Часы Плата
1 1.5 2.00
2 4.0 2.50
3 24.0 10.00
Итого 29.5 14.50

#include <iostream>
#include <fstream>
#include <iomanip>

using namespace std;

struct parking{
int num;
double hours;
};

double calculateCharges(double hours,int n);

int main(){
ifstream in;
ofstream out;
char path[20];
int n;
cout<<"Enter path to file(with extension)"<<endl;
cin>>path;
in.open(path);
out.open("result.txt");
double total = 0,revenue = 0;
if(!in.is_open()){
cout<<"File doesn't exist"<<endl;
}
else {
cout<<"Payments are counted, check you file"<<endl;
in>>n;
parking a[n];
for(int i=0;i<n;i++){
in>>a[i].num;
in>>a[i].hours;
}
out<<"Automobile "<<"Hours "<<"For pay"<<endl;

for(int i=0;i<n;i++){
out<<setw(6)<<a[i].num<<" ";

out<<setw(11)<<setprecision(3)<<setiosflags(ios::showpoint)<<a[i].hours<<" ";
out<<setw(7)<<calculateCharges(a[i].hours,n)<<endl;
total += a[i].hours;
revenue += calculateCharges(a[i].hours,n);
}
out<<" "<<setw(2)<<"Total"<<"
"<<setw(11)<<total<<setw(8)<<revenue;
}
in.close();
out.close();
return 0;
}

double calculateCharges(double hours,int n){


double cost;
for(int i=0;i<n;i++){
if(hours<=3){
cost = 2;
}
else if(hours>=19){
cost = 10;
}
else {
cost = 2+0.50*(hours-3);
}
}
return cost;
}

Вам также может понравиться