C++ Walkthrough cout.setf(ios::fixed); and cout.precision(); - c++

/* Problem 38 */
#include <iostream>
using namespace std;
class abc {
double n;
public:
abc() { n = 67.5; cout << "1\n"; }
abc(double num) { set(num); cout << "2\n"; }
double get() const { cout<<"3\n"; return n; }
virtual void set(double num) {
if (num < 10)
n = 10;
else if (num > 100)
n = 100;
else
n = num;
cout << "4\n";
}
};
class def: public abc {
double m;
public:
def() { m = 6.2; cout << "5\n"; }
def(double num1, double num2): abc(num1) {
set(num2 - abc::get()); cout << "6\n"; }
double get() const {
cout << "7\n"; return m + abc::get(); }
void set(double num) {
if (num < 10 || 100 < num)
m = num;
else
m = 55;
cout << "8\n";
}
};
void do_it(abc &var, double num)
{ cout << var.get() << '\n';
var.set(num);
cout << var.get() << '\n';
}
int main()
{ abc x(45);
def y(2, 340);
cout.setf(ios::fixed);
cout.precision(3);
do_it(x, 200);
do_it(y, 253);
cout << x.get() << '\n';
cout << y.get() << '\n';
return 0;
}
With the above code I just wanted to know what below two lines will really do in the above code
cout.setf(ios::fixed);
cout.precision(3);
Please do not just give me answer some explanation would be so appreciated because I'm doing a walkthrough to prepare for my final exam tomorrow.
I searched and some source says it is to set flags but really I don't get what is the concept of it and how it works

cout.setf(ios::fixed)
makes cout print floats with a fixed number of decimals and
cout.precision(3)
sets this number to be three.
For example, if you got a
double f = 2.5;
then
cout << f;
will print
2.500

Great documentation about how to format your output : Output formatting
It's always usefull when you're trying to do a command-line UI.

#include<iostream>
using namespace std;
int main(){
float large = 2000000000;
cout << large;
return 0;
}
The output will be in scientific notation as:
2e+009
In order to get the value as it is you should use cout.setf(ios::fixed)
#include<iostream>
using namespace std;
int main(){
cout.setf(ios::fixed);
float large = 2000000000;
cout << large;
return 0;
}
The output will be as it is with default precision which is 6 for float.
2000000000.000000
You can set the precision in the above code as:
cout.precision(7);
.....

It's similar to including the manipulation library:
include :
<iomanip>
And then using the following functions
cout << fixed << showpoint;
cout << setprecision(3);

Related

I am getting different results while using different compilers

While trying out a question related to armstrong number i am getting different answers in VS-Code and Programiz online compiler https://www.programiz.com/cpp-programming/online-compiler/ ..
#include<iostream>
#include<math.h>
using namespace std ;
int main(){
int number ;
cin >> number ;
int sum = 0;
int original = number;
while (number > 0)
{
int element ;
element = number%10 ;
sum = sum + pow(element,3) ;
number = number/10 ;
}
cout << sum << endl ;
cout << number << endl ;
cout << original << endl ;
if (sum == original)
{
cout << "It is an Armstrong number " << endl ;
}
else cout << "It is not an Armstrong number " << endl ;
}
This was the output on vs code .
This was the output on programiz compiler ...
Pls do enlighten as to why is this happening and how can this be corrected ..
Write your own integer power function e.g.
(the constexpr allows the static_assert tests at compile time)
#include <cmath>
#include <iostream>
#include <type_traits>
static constexpr unsigned int int_pow(unsigned int value, unsigned int power)
{
int result{ 1 };
for (int i = power; i > 0; --i)
{
result *= value;
}
return result;
}
int main()
{
static_assert(int_pow(10, 3) == 1000);
static_assert(int_pow(2, 3) == 8);
return 0;
}

Not taking the input

I want to write a program that only takes odd numbers, and if you input 0 it will output the addition and average, without taking any even number values to the average and the addition. I'm stuck with not letting it take the even values..
Heres my code so far:
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin >> num;
numberOfInputs++;
addition = addition + num;
if (num % 2 != 0) {
//my issue is with this part
cout << "ignored" << endl;
}
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
}
}
Solution of your code:
Your code doesn't working because of following reasons:
Issue 1: You adding inputs number without checking whether it's even or not
Issue 2: If would like skip even then your condition should be as follow inside of the loop:
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
Solving your issues, I have update your program as following :
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num = 0;
int addition = 0;
int numberOfInputs = 0;
cout << "Enter your numbers (only odd numbers), the program will continue asking for numbers until you input 0.." << endl;
for (; ;) {
cin>> num;
if (num%2==0) {
cout << "ignored:" <<num << endl;
continue;
}
numberOfInputs++;
addition = addition + num;
if (num == 0) {
cout << "Addition: " << addition << endl;
cout << "Average: " << addition / numberOfInputs << endl;
break;
}
}
}
#include <iostream>
#include <stdio.h>
using namespace std;
int main() {
int number;
int sum=0;
int average=0;
int inputArray[20]; // will take only 20 inputs at a time
int i,index = 0;
int size;
do{
cout<<"Enter number\n";
cin>>number;
if(number==0){
for(i=0;i<index;i++){
sum = sum + inputArray[i];
}
cout << sum;
average = sum / index;
cout << average;
} else if(number % 2 != 0){
inputArray[index++] = number;
} else
cout<<"skip";
}
while(number!=0);
return 0;
}
You can run and check this code here https://www.codechef.com/ide
by providing custom input

crash when reading from a file

first of all, i'd like u to know that im a college student (our syllabus in programming is not that advanced yet)(Btw im not asking for answers to my assignments etc, im just practicing).
Ok so i have 2 problems
Some function in my code changes the value of my array (when i dont want it to)
I really have no idea, but it seems that getting some values from a file to store into my array crashes the program, furthermore, after fiddling a bit with the code (i have no idea what changed), it no longer crashes during the said part, BUT it still crashes at the end of the code execution..
i hope u guys could help me, i've been searching whole day long.
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
void readFile (float x[], int &y) {
ifstream load;
string filename;
cout << "Enter the name of the file: ";
cin >> filename;
load.open(filename.c_str());
while (!load.eof()) {
load >> x[y];
y++;
}
if (!load) {
cout << "asd";
}
}
void computeC (float x[], int y, float z[]) {
int v=0;
for (v=0; v<=y; v++) {
z[v] = (5 * (x[v] - 32)/9);
}
}
float average (float x[], int y) {
int v=0;
float sum=0;
for (v=0; v<=y; v++) {
sum += x[v];
}
return sum / v;
}
void grade (float x[], char grades[], int y, int &hi, int &med, int &lo) {
int v=0;
hi = med = lo = 0;
for (v=0; v<=y; v++) {
if ( x[v] >= 35) {
grades[v] = 'H';
hi++;
}
else if ( (x[v] < 35) && (x[v] >= 20) ) {
grades[v] = 'M';
med++;
}
else if ( x[v] < 20 ) {
grades[v] = 'L';
lo++;
}
}
}
void writeFile (float x[], float y[], int z, char w[]) {
ofstream save;
int v=0;
for (v=0; v <= z; v++) {
cout << "C(Celcius)" << left << setw(5);
cout << "F(Farenheit)" << left << setw(5);
cout << "Description\n";
cout << right << setw(7) << y[v];
cout << left << setw(8) << x[v];
cout << left << setw(8) << w[v];
}
}
int main(int argc, char** argv) {
int ctr=0, high, medium, low;
float F[ctr], C[ctr], ave;
char grades[ctr];
readFile (F, ctr);
computeC (F, ctr, C);
ave = average (C, ctr);
grade (C, grades, ctr, high, medium, low);
cout << "Average of the temperatures: " << ave << endl;
cout << "Number of high temperatures: " << high << endl;
cout << "Number of medium temperatures: " << medium << endl;
cout << "Number of low temperatures: " << low << endl;
//writeFile (F, C, ctr, grades);
return 0;
}
(Code from https://drive.google.com/file/d/0BxeZTCUL3Q4oZHlqWFdjMDZub0E/view?usp=sharing)
Without checking the whole code I can directly think of some parts of the code.
Let me start with
while (!load.eof()) {
load >> x[y];
y++;
}
Where you write more values than x[] can hold and your program will crash in that case.
Make sure to only write to your array up to the maximum allocated memory.
The problem is that !load.eof() will not do what you expect it to do as it will be read from beyond the end of the file. It will execute your loop one more time too much.
Second:
int ctr=0, high, medium, low;
float F[ctr], C[ctr], ave;
char grades[ctr];
ctr is 0 so you declare Arrays of F, c and grades with 0 elements. That's not very clever ;) You can't read or write from them.

C++ Sum of factorial -Request 2nd code

I would like to analyze the complexity of my code algorithm.Therefore,i must have 2 different programs giving the same functions to allow me to start off.
Currently this is my own code.
I'm not sure if it is allowed that i would like to have someone that could volunteer his own way code to compute summation of factorial for me as the 2nd program code.
Preferrably a nested loop.
#include <iostream>
using namespace std;
int main()
{
int val;
int i;
int a = 0;
int c = 1;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
for (i = 1; i <= val; i++)
{
c = c * i;
a = a + c;
}
cout << "The sum of the factorials is " << a << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int val;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
static const int results[] = {
0, 1, 3, 9, 33, 153, 873, 5913, 46233, 409113,
4037913, 43954713, 522956313
};
cout << "The sum of the factorials is " << results[val < 0 ? 0 : val] << endl;
system("pause");
return 0;
}
Note that I replicated the defect in the original program which causes it to return the incorrect value if the user enters 0.
This alternate version assumes 32-bit integers because it takes advantage of overflow behavior. Extending to 64-bit integers is left as an exercise.
I do not understand what you do with another nested way but i hope this can help...
#include <iostream>
using namespace std;
int main()
{
int val;
int i;
int a = 0;
int c = 1;
cout << "Please enter a number: ";
cin >> val;
cout << endl;
for (i = 1; i <= val; i++){
c *= i;
a += c;
}
int c2=1;
for (i = val; i > 1; i--){
c2*=i;
c2++;
}
cout << "The sum of the factorials is " << a << endl;
cout << "The sum of the factorials is " << c2 << endl;
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main()
{
int suma = 0;
int n = 0;
cout << "Sum of factorials\n";
cout << "-------------------------------\n";
cout << "Insert number of n: ";
cin >> n;
int i = 1;
while (i <= n)
{
int factorial = 1;
for(int j=1; j<=i; j++)
{
factorial = factorial * j;
}
suma += factorial;
i++;
}
cout << "Sum of factorials is: " << suma;
system("pause");
return 0;
}

for loop character printing [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
.....................HEY GUYS,I GOT THE ANSWER.PLEASE CHECK OUT AT BOTTOM.....................
ThAnKs FoR aLl ThOsE wHo TrYiNg tO hElP mE!
How to print all the character outside the for-loop that input inside for-loop? It only prints the last character entered in for-loop
input all 4 names of items and price in void shop::getdata()
output of this only prints the name of item that entered last in void shop::getdata() for 4 times in void shop::putdata()
output of price is correct,it prints orderly.
what's the problem with the name of item?
Question:WAP to store pricelist of 5 items & print the largest price as well as the sum of all prices & pricelist also.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class shop
{
int i;
char item[50];
float price[50];
public:
void getdata();
void putdata();
float sum();
float lar();
};
void shop::getdata()
{
for(i = 0; i <= 4; i++)
{
cout << "Enter the item name:" << "\n";
cin >> item;
cout << "Enter price:" << "\n";
cin >> price[i];
}
}
void shop::putdata()
{
cout << "\t\tPRICE LIST" << "\n";
cout << "\t\t**********" << "\n";
cout << "ITEM NAME\t\t\tPRICE" << "\n";
cout << "*********\t\t\t*****" << "\n";
for(i = 0; i <= 4; i++)
{
cout << item << "\t\t\t\t";
cout << price[i] << "\n";
}
}
float shop::sum()
{
float sum = 0;
for( i= 0; i <= 4; i++)
{
sum = sum + price[i];
}
cout << "\t\t\t\tsum is:" << sum << "\n";
return sum;
}
float shop::lar()
{
float lar;
lar = price[0];
for(i = 0; i <= 4; i++)
{
if (price[i] > lar)
lar = price[i];
}
cout << "\t\t\tlargest is:" << lar;
return lar;
}
void main()
{
shop x;
int c;
clrscr();
x.getdata();
do
{
cout << "\n\n1.PRICE LIST\n";
cout << "2.SUM\n";
cout << "3.LARGEST\n";
cout << "4.EXIT\n";
cout << "Enter your choice\n";
cin >> c;
switch (c)
{
case 1:
x.putdata();
break;
case 2:
x.sum();
break;
case 3:
x.lar();
break;
default:
cout << "PRESS ANY KEY TO EXIT\n";
break;
}
}
while(c >= 1 && c <= 3);
getch();
}
ANSWER
#include<iostream.h>
#include<conio.h>
#include<string.h>
class shop
{
int i;
char item[50];
float price;
float e[10];
public:
void getdata();
void putdata();
float sum();
float lar();
};
void shop::getdata()
{
cout << "Enter the item name:" << "\n";
cin >> item;
cout << "Enter price:" << "\n";
cin >> price;
}
void shop::putdata()
{
cout << item << "\t\t\t\t";
cout << price << "\n";
}
float shop::sum()
{
float sum = 0;
for( i= 0; i <= 4; i++)
{
cout<<"Enter prices"<<"\n";
cin>>e[i];
sum = sum + e[i];
}
cout << "\t\t\t\tsum is:" << sum << "\n";
return sum;
}
float shop::lar()
{
float lar;
lar = e[0];
for(i = 0; i <= 4; i++)
{
if (e[i] > lar)
lar = e[i];
}
cout << "\t\t\tlargest is:" << lar;
return lar;
}
void main()
{
shop x[10];
int c,i;
clrscr();
for(i=0;i<=4;i++)
x[i].getdata();
do
{
cout << "\n\n1.PRICE LIST\n";
cout << "2.SUM\n";
cout << "3.LARGEST\n";
cout << "4.EXIT\n";
cout << "Enter your choice\n";
cin >> c;
switch (c)
{
case 1:
for(i=0;i<=4;i++)
x[i].putdata();
break;
case 2:
x[i].sum();
break;
case 3:
x[i].lar();
break;
default:
cout << "PRESS ANY KEY TO EXIT\n";
break;
}
}
while(c >= 1 && c <= 3);
getch();
}
It's a little hard to tell what you're asking (you would do well to indent your code and ask a clearer question), but I think your problem (well, the main one you're referring to!) is how you're handling item names.
You've declared your shop to contain an array of 50 chars - that is, 50 single characters. Since you have an array of 50 prices, you almost certainly wanted an array of 50 strings. In basic C, that would be char *item[50], an array of 50 dynamically-allocated char arrays. Since you've tagged this as C++, though, you're better off using a string.
A slightly more modern shop would look like this:
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::ostream;
using std::string;
using std::vector;
class Item {
string m_name;
double m_price;
public:
Item(const string &name, double price)
: m_name(name), m_price(price) {
};
string name() const { return m_name; }
double price() const { return m_price; }
};
class Shop {
vector<Item> m_items;
public:
void readData();
void writeData() const;
double getPriceSum() const;
double getMaxPrice() const;
};
void Shop::readData() {
for (;;) {
string name, end_of_line;
double price;
cout << "Enter the item name (or nothing to finish input): ";
getline(cin, name);
if (name == "") {
break;
}
cout << "Enter the price: ";
cin >> price;
// the previous ">>" left the end-of-line in the stream,
// so read it now.
getline(cin, end_of_line);
m_items.push_back(Item(name, price));
}
}
void Shop::writeData() const {
for (size_t i = 0; i < m_items.size(); i++) {
const Item &item = m_items[i];
cout << item.name() << "\t" << item.price() << "\n";
}
}
double Shop::getPriceSum() const {
double sum = 0.0;
for (size_t i = 0; i < m_items.size(); i++) {
sum += m_items[i].price();
}
return sum;
}
double Shop::getMaxPrice() const {
double max = 0.0; // assume that all prices are positive
for (size_t i = 0; i < m_items.size(); i++) {
max = std::max(max, m_items[i].price());
}
return max;
}
int main() {
Shop shop;
shop.readData();
shop.writeData();
cout << "sum: " << shop.getPriceSum() << "\n";
cout << "max: " << shop.getMaxPrice() << "\n";
return 0;
}
It is not perfect C++ style, but still makes the code easy to read.