Как изменить форматированный вывод данных с printf на cout?
Как можно изменить в программе вывод данных с printf на cout?
Код программы:
#include <math.h>
#include <iostream>
#include <cmath>
#include <conio.h>
#include <string>
#include <windows.h>
using namespace std;
const int dlx = 6;
const int dlxx = 3;
const int dly = 15;
const int dlyy = 8;
const int col = 2;
const int str = 10;
const double e = 2.718281828459045;
const double PI = 3.14159265;
void func(double& x, double& y, double p)
{
if (x > atan(p)) {
y = pow(log10(1 + abs(p * x)), 2);
}
else y = y = ((cos(x * x) / (4 + p)) / pow(PI + x * x, 1 / 3));
}
void table()
{
int i, j;
for (j = 1; j <= col; j++) {
cout << "! ";
for (i = 1; i <= dlx; i++)
cout << "-";
cout << " ! ";
for (i = 1; i <= dly; i++)
cout << "-";
cout << " !";
}
cout << endl;
}
int main()
{
SetConsoleCP(1251);
SetConsoleOutputCP(1251);
const double xn = -2.0, xk = 4.0;
double y, x, h = 0.02, p;
int page = 1, i = 0, j = 0, ii = 0, jj = 0, output;
do
{
cout << "Введите параметр P в пределе |P|<=5";
cin >> p;
} while (abs(p) >= 5);
cout << "Введите вывод значения функции (1) научный (2) с плавающей точкой";
cin >> output;
x = xn;
while (x <= xk + h) {
system("cls");
cout << "PAGE # " << page << endl;
cout << "\t" << "\t" << "\t" << "\t";
cout << "Таблица значений функции" << endl;
cout << "\t" << "\t" << "\t" << "\t";
cout << "При P = " << p << endl;
table();
for (i = 1; (i <= str) && (x <= xk + h); i++)
{
for (j = 1; (j <= col) && (x <= xk + h); j++)
{
func(x, y, p);
cout << "! ";
printf("%*.*lf", dlx, dlxx, x); //изменить здесь
cout << " ! ";
if (output == 1)
{
printf("%*e !", dly, y); //Изменить здесь
}
else
printf("%*.*lf !", dly, dlyy, y); //изменить здесь
x = x + h;
}
cout << endl;
table();
}
_getch();
page++;
}
}
Ответы (1 шт):
Автор решения: EOF
→ Ссылка
Вот пример с использованием iomanip (это заголовчный файл, который нужно подключить). Вот что используется:
setwустанавливает ширину поля выводаsetprecisionустанавливает количество знаков после десятичной точкиfixedустанавливет режим отображения с плавающей точкой даже для больших чиселscientificустанавливает научную нотацию (это как режимeдляprintf)
//printf("%*.*lf", dlx, dlxx, x);
cout << fixed << setw(dlx) << setprecision(dlxx) << x;
//printf("%*e !", dly, y);
cout << scientific << setw(dly) << y << " !";
//printf("%*.*lf !", dly, dlyy, y);
cout << fixed << setw(dly) << setprecision(dlyy) << y << " !";