Priority:
I am quite new at this obviously. I have tried reading other peoples errors for what I have and can't find a fix. When I take out the ofstream bit and switch fOut for cout then program works fine but I cant seem to get it to output to a file. I did make the file in advance.
Secondary:
I am suppose to also somehow use 1 loop for the range of x should be 0 to 10 in steps of 1, 10 to 50 in steps of 5( In the SquareMachine function). Same rule of 1 loop for the bit in main with 0 to 15 in 1 degree increments and 15 to 45 in 5 degree increments. I am sure there is a technique I am simply not seeing to combine my loops or perhaps a loop... hole.. hah get it? Anyway, primarily need assistance with the output file.
Thank you for any advice/assistance
Error(s):
week4.cpp: In function ‘void ShowProgramHeader()’:
week4.cpp:34: error: ‘fOut’ was not declared in this scope
week4.cpp: In function ‘int main()’:
week4.cpp:44: error: ‘struct std::ofstream’ has no member named ‘is’
week4.cpp: In function ‘int SquareMachine()’:
week4.cpp:92: error: ‘fOut’ was not declared in this scope
Code:
#include <cmath>
#include<stdlib.h>
#include <iostream>
#include t<ime.h>
#include<cstdlib>
#include<unistd.h>
#include<iomanip>
#include<fstream>
using namespace std;
//Global Variable(s)
long fact(long n);
// Prototype(s)
int SquareMachine();
// Program Header
void ShowProgramHeader()
{
fOut << "Name" << endl;
fOut << "Class and Date \n\n\n" << endl;
}
//Command Center
int main()
{
ofstream fOut( "sTable.out", ios::out| ios::trunc);
if( fOut.is.open())
{
ShowProgramHeader();
SquareMachine();
fOut << "Value---Output\n"<<endl;
for( long t =0; t <=15; t++)
{
fOut << setw(10) << t;
fOut << setw(20) << fact(t) << endl;
}
for( long t =20; t <=45; t=t+5)
{
fOut << setw(10) << t;
fOut << setw(20) << fact(t) << endl;
fOut.close();
}
}
else
cout<<"Unable to Open the file: sTable.out";
exit(-1);
}
long fact(long n)
{
if( n ==0 || n==1 )
return 1;
else if( n==2 || n <= 15)
return n * fact( n-1);
else if( n <=15 || n <=45)
return n * fact (n-5);
}
int SquareMachine()
{
double x = 10;
int n = 2;
double z;
fOut << "\nNumber Sqrt Exp Pow\n";
for ( z=0; z<=x; ++z)
{
fOut << setw(10) << left << z << setprecision(2);
fOut << setw(10) << left << sqrt(z) << setprecision(3);
fOut << setw(10) << left << exp(z) << setprecision(10);
fOut << setw(10) << left << pow(z,n) << setprecision(4);
fOut << "\n" ;
}
for ( z=15; z<=50; z= z+5)
{
fOut << setw(10) << left << z << setprecision(2);
fOut << setw(10) << left << sqrt(z) << setprecision(3);
fOut << setw(10) << left << exp(z) << setprecision(10);
fOut << setw(10) << left << pow(z,n) << setprecision(4);
fOut << "\n" ;
}
fOut << " \n End of Part 1\n"<< endl;
}
You have numerous errors in your code. Mostly optimization errors, also some typos. But always, you should listen to your compiler first, because it helps you find the problem. It is designed to do so!
Sometimes it literally says what you should do (or what not) in a case of error.
For example your compiler says:
week4.cpp: In function ‘void ShowProgramHeader()’:
week4.cpp:34: error: ‘fOut’ was not declared in this scope
It means that in that function's scope fOut cannot be seen. It is because it was declared in the main() function, so it is a local variable (only avaiable in a scope) and not global (avaiable from everywhere). If you want to use this variable in other functions too, it is a good practice to use references or pointers. (I would recommend you using global variables only if you really need to do so, in special cases)
Included headers: (don't include unnecessary headers)
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <cmath> // for Mathematical functions
Function prototypes:
void ShowProgramHeader(std::ofstream&);
long fact(long);
int SquareMachine(std::ofstream&);
Client code:
int main() {
std::ofstream f_out("sTable.txt", std::ios::out | std::ios::trunc);
if(f_out.is_open()) {
ShowProgramHeader(f_out);
SquareMachine(f_out);
f_out << std::endl << std::left << std::setw(10) << "Number";
f_out << std::left << std::setw(10) << "Output" << std::endl;
long i = 0; // for fact(long)
while(i <= 45) {
if(i <= 15 || i >= 20) {
f_out << std::left << std::setw(10) << i;
f_out << std::left << std::setw(10) << fact(i) << std::endl;
if(i <= 15) i++;
else i += 5;
} else i++;
}
f_out.close();
}
else {
std::cerr << "Unable to Open the file: sTable.out";
return -1;
}
return 0;
}
Function implementations from here!
Header (I'm not really sure what you are planning to do with this function):
void ShowProgramHeader(std::ofstream& f_out) { f_out << "Name\nClass and Date\n"; }
Square machine:
int SquareMachine(std::ofstream& f_out) {
f_out << std::endl << std::left << std::setw(10) << "Number";
f_out << std::left << std::setw(10) << "Square";
f_out << std::left << std::setw(20) << "Exp";
f_out << std::left << std::setw(10) << "Power" << std::endl;
float i = 0;
while (i <= 50) {
if(i <= 10 || i >= 15) {
f_out << std::left << std::setw(10) << std::setprecision(2) << i;
f_out << std::left << std::setw(10) << std::setprecision(3) << std::sqrt(i);
f_out << std::left << std::setw(20) << std::setprecision(10) << std::exp(i);
f_out << std::left << std::setw(10) << std::setprecision(4) << std::pow(i, 2) << std::endl;
if(i <= 10) i++;
else i += 5;
} else i++;
}
f_out << std::endl << "End of Part 1" << std::endl;
}
And finally the recursive factorial function! (You overcomplicated your solution, if you meant to use the factorial method). Also note that when your factorial's value becomes so big, you have to handle it. You should find a type that can store larger numbers than long!
long fact(long n) {
if(n <= 1) return 1;
return n * fact(n - 1);
}
Output (I used sTable.txt instead of sTable.out)
Name
Class and Date
Number Square Exp Power
0 0 1 0
1 1 2.718281746 1
2 1.41 7.389056206 4
3 1.73 20.08553696 9
4 2 54.59814835 16
5 2.24 148.4131622 25
6 2.45 403.4288025 36
7 2.65 1096.633179 49
8 2.83 2980.958008 64
9 3 8103.083984 81
10 3.16 22026.46484 100
15 3.87 3269017.25 225
20 4.47 485165184 400
25 5 7.200490291e+010 625
30 5.48 1.068647422e+013 900
35 5.92 1.586013445e+015 1225
40 6.32 2.353852703e+017 1600
45 6.71 3.493427058e+019 2025
50 7.07 5.184705458e+021 2500
End of Part 1
Number Output
0 1
1 1
2 2
3 6
4 24
5 120
6 720
7 5040
8 40320
9 362880
10 3628800
11 39916800
12 479001600
13 1932053504 // long storage problem starts from here
14 1278945280 // wrong!
15 2004310016 // wrong!
20 -2102132736 // wrong!
25 2076180480 // wrong!
30 1409286144 // wrong!
35 0 // wrong!
40 0 // wrong!
45 0 // wrong!
Since long can contain a value up to ~2,1*10^9, however 13! ~ 6*10^9!
Related
I created a multiplication table for the integers 1...10. Here is the code:
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 10; j++) {
std::cout << "\t" << i * j;
}
std::cout << std::endl;
}
And my output is this:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
The problem I am struggling with is that I need to insert a random number that represents an error value inside the multiplication table. For example:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 13 15 18 21 24 27 30
As you can see in this example, the error value is 13 where 3 x 4 = 12, but instead there is the number 13.
Should I use another loop to insert the random number? If so, how to go about it?
You can use <random> header file for this.
std::random_device rd;
std::mt19937 gen(rd());
// it produces uniformly distributed random integers in the range [a, b] (both inclusive)
std::uniform_int_distribution<> dis(0, 1); // either add 0 or 1 (1 will be the error -- can change a,b according to your need)
for (int i = 1; i <= 10; i++)
{
for (int j = 1; j <= 10; j++)
{
std::cout << "\t" << i * j + dis(gen); // just add the error value to your multiplication
}
std::cout << std::endl;
}
#include <iostream> // input/output
#include <random>
struct FieldData {
using Row = unsigned int;
using Col = unsigned int;
const Row rows{10};
const Col cols{10};
Row err_row;
Col err_col;
unsigned int err_value;
FieldData() {} // use default values for rows/cols
FieldData(Row max_row, Col max_col) : rows(std::move(max_row)), cols(std::move(max_col)) {} // use given values for rows/cols
};
void print_field(const FieldData& data)
{
for (FieldData::Row row=1;row <= data.rows; row++)
{
for (FieldData::Col col = 1; col <= data.cols; col++)
{
if (row == data.err_row && col == data.err_col)
std::cout << "\t" << data.err_value;
else
std::cout << "\t" << row*col;
}
std::cout << std::endl;
}
}
FieldData get_field(std::mt19937& generator)
{
FieldData data;
std::uniform_int_distribution<FieldData::Row> dist_rows(1, data.rows); // random for row
std::uniform_int_distribution<FieldData::Row> dist_cols(1, data.cols); // random for col
std::uniform_int_distribution<FieldData::Row> dist_result(1, data.rows*data.cols); // random for result
data.err_row = dist_rows(generator);
data.err_col = dist_cols(generator);
data.err_value = dist_result(generator);
if (data.err_value != data.err_row*data.err_col)
data.err_value--; // avoid correct value on error pos
return data;
}
int main()
{
std::random_device rd;
std::mt19937 generator(rd());
while (true)
{
auto field = get_field(generator);
print_field(field);
// some code to ask the user and so on.... (std::cin ...)
std::cout << "Error value '" << field.err_value << "' is on row " << field.err_row << ", col " << field.err_col << std::endl;
// if (... some code to check if user wants to break...)
break;
// code to go on
// go on
std::cout << std::endl;
}
}
As requested by the questioner, a version without further constructs:
#include <iostream> // input/output
#include <random>
int main()
{
std::random_device rd;
std::mt19937 generator(rd());
unsigned int rows = 10;
unsigned int cols = 10;
std::uniform_int_distribution<unsigned int> dist_rows(1, rows); // random for row (1 to value of field_rows)
std::uniform_int_distribution<unsigned int> dist_cols(1, cols); // random for col (1 to value of field_cols)
std::uniform_int_distribution<unsigned int> dist_result(1, rows * cols); // random for result
while (true) // infinite loop - must be interrupted explicitly with break or similar
{
unsigned int err_row = dist_rows(generator); // Generate the random number that defines the row
unsigned int err_col = dist_cols(generator); // Generate the random number that defines the col
unsigned int err_value = dist_result(generator); // Generate the random value
if (err_value != err_row * err_col)
err_value--; // avoid correct value on error position - simple decrement the value
// print_field
for (unsigned int row = 1; row <= rows; row++)
{
for (unsigned int col = 1; col <= cols; col++)
{
if (row == err_row && col == err_col) // condition to insert the error value
std::cout << "\t" << err_value;
else
std::cout << "\t" << row * col;
}
std::cout << std::endl;
}
//
// some code to ask the user and so on.... (std::cin ...)
//
std::cout << "Error value '" << err_value << "' is on row " << err_row << ", col " << err_col << std::endl;
// if (... some code to check if user wants to break...)
break;
// code to go on
// go on
std::cout << std::endl;
}
}
I hope this answer helps you, I have separated the different parts a little bit to make it more clearly arranged for you. The code should at least give you a rough idea how something like this could be implemented. Depending on the use case, a separate class or something similar would of course be appropriate.
The code in the second variant differs from the functionality only in that the uniform_int_distributions are outside the while(true) scope and thus are not always "rebuilt" as is the case in the first variant (since more dynamic and modularity would have been possible in principle).
Should I use another loop to insert the random number? If so, how to go about it?
You're only inserting one error, so it doesn't make much sense to a loop for that.
Well, why don't you first decide where the random number goes? Once you know that, you can modify the inner loop body, as follows:
int value = i * j;
if ((i == error_location.row) and (j = error_location.column)) {
value = // code for introducing an error, e.g. sample a random answer,
// or a random offset added to the correct answer etc.
}
std::cout << "\t" << i * j;
The decision of a position for the erroneous values can be made using the C++ header, as explained in this question. In your case it would be something like the following:
constexpr const int table_leg { 10 };
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> coordinate_distribution(0, table_leg - 1);
struct { int row, col; } error_location =
{ coordinate_distribution(gen), coordinate_distribution(gen) };
Notes:
I suggest replacing i with row or row_index and j with col or column or column_index; also, using the named constant instead of repeating the "magic number" 10.
I've assumed you don't want to store your multiplication table in a buffer, then replace one value in there with an error. If you are storing the table somewhere, you could avoid the complicated inner loop and just set the error after filling in all the correct values.
So thank's to everyone's input - especially #Wolfgang.
I did read up on C++11's random header file and it's functions.
I did create a source code with random functions and one without.
Any feed would be appreciated on how to make my source code more efficient.
Other than that, it achieves what I needed it to do.
#include <iostream>
#include <ctime>
#include <iomanip>
const unsigned int ROWS = 10;
const unsigned int COLUMNS = 10;
void randomValue(unsigned int &, unsigned int &, unsigned int &);
int main()
{
unsigned int rValue;
unsigned int cValue;
unsigned int pValue;
unsigned int rowError;
unsigned int columnError;
unsigned int productError;
unsigned int userRowGuess;
unsigned int userColumnGuess;
char choice;
do
{
randomValue(rValue, cValue, pValue);
std::cout << "\033[2J\033[0;0H"; // This code clears the screen
std::cout << std::endl << std::endl;
std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
std::cout << std::setw(35) << "+ Multiplication Table +" << std::endl;
std::cout << std::setw(35) << "++++++++++++++++++++++++" << std::endl;
std::cout << std::endl << std::endl;
while (true)
{
rowError = rValue;
columnError = cValue;
productError = pValue;
if (productError == rowError * columnError)
{
productError--;
}
for (unsigned int row = 1; row <= ROWS; row++)
{
for (unsigned int column = 1; column <= COLUMNS; column++)
{
if (row == rowError && column == columnError)
{
std::cout << "\t" << "" << productError;
}
else
{
std::cout << "\t" << row * column;
}
}
std::cout << std::endl;
}
break;
}
std::cout << std::endl << std::endl;
std::cout << "\t\t" << "Type in the column number " << std::endl;
std::cout << "\t\t" << "of the location of the " << std::endl;
std::cout << "\t\t" << "error & then press " << std::endl;
std::cout << "\t\t" << "[Enter]: ";
std::cin >> userColumnGuess;
std::cout << std::endl;
std::cout << "\t\t" << "Type in the row number " << std::endl;
std::cout << "\t\t" << "of the location of the " << std::endl;
std::cout << "\t\t" << "error & then press " << std::endl;
std::cout << "\t\t" << "[Enter]: ";
std::cin >> userRowGuess;
std::cout << std::endl;
if (userRowGuess != rowError && userColumnGuess != columnError)
{
std::cout << "\t\t" << "Your answer was incorrect!" << std::endl << std::endl;
std::cout << "\t\t" << "Error value '" << productError << "' is located" << std::endl;
std::cout << "\t\t" << "on row " << rowError << ", column " << columnError << "." << std::endl;
}
else
{
std::cout << "\t\t" << "You are correct! You win!" << std::endl;
}
std::cout << std::endl;
std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
std::cout << "\t\t" << "Type in 'Y' for yes or 'N'" << std::endl;
std::cout << "\t\t" << "for no & then press [Enter]: ";
std::cin >> choice;
while (choice != 'y' && choice != 'Y' && choice != 'n' && choice != 'N')
{
std::cout << std::endl;
std::cout << "\t\t" << "Invalid entry. Only 'Y' or 'N'" << std::endl;
std::cout << "\t\t" << "are accepted answers." << std::endl << std::endl;
std::cout << "\t\t" << "Would you like to play again?" << std::endl << std::endl;
std::cout << "\t\t" << "Type in 'Y' for yes or 'N' for" << std::endl;
std::cout << "\t\t" << "no & then press [Enter]: ";
std::cin >> choice;
}
std::cout << std::endl;
} while (choice == 'y' || choice == 'Y');
std::cout << "\t\t" << "Press [Enter] to continue....." << std::endl;
std::cin.get();
std::cin.get();
return 0;
}
void randomValue(unsigned int &rValue, unsigned int &cValue, unsigned int &pValue)
{
srand((unsigned)time(NULL));
unsigned int r = rValue = (rand() % ROWS) + 1;
unsigned int c = cValue = (rand() % COLUMNS) + 1;
unsigned int p = pValue = (rand() % (ROWS * COLUMNS)) + 1;
}
In this little program I try to order 3 numbers in a descending order. But seems like the line in which has "// 3 2 1 - doesn't work" as a comment isn't working as expected. It seems like my logic is correct.
My input:
4,
554 and
454545
Output: (which is not what I wanted)
554, 454545 and 4
If the value hold on the integer numbThree is bigger than numbOne and if numbOne is NOT bigger than numbTwo (NOT == else) it should ouput numbThree, numbTwo and numbOne in this order, why doesn't it work?
#include <iostream>
int main() {
int numbOne = 0, numbTwo = 0, numbThree = 0;
std::cin >> numbOne >> numbTwo >> numbThree;
if (numbOne > numbTwo) {
if (numbTwo > numbThree) {
std::cout << numbOne << " " << numbTwo << " " << numbThree << std::endl; // 1 2 3
}
else {
std::cout << numbOne << " " << numbThree << " " << numbTwo<< std::endl; // 1 3 2
}
}
else if (numbTwo > numbOne) {
if (numbOne > numbThree) {
std::cout << numbTwo << " " << numbOne << " " << numbThree << std::endl; // 2 1 3 - works
}
else {
std::cout << numbTwo << " " << numbThree << " " << numbOne << std::endl; // 2 3 1
}
}
else if (numbThree > numbOne) {
if (numbOne > numbTwo) {
std::cout << numbThree << " " << numbOne << " " << numbTwo << std::endl; // 3 1 2
}
else {
std::cout << numbThree << " " << numbTwo << " " << numbOne << std::endl; // 3 2 1 - doesn't work
}
}
std::cin.get();
std::cin.ignore();
return 0;
}
Thanks in advance for helping me out.
You cannot, in general, sort 3 numbers with 2 comparisons (see YSC's comment for a hard reason in terms of information content). Already your case 1 3 2 is flawed: what if numbThree > numbOne?
In general you have to allow for up to 3 comparisons. Of course, you can simply use the sort functionality provided by the standard library (i.e. by the language). If you don't want to (for some reason), then the correct logic (for ascending order) is
if(a<b)
if (b<c) // a,b,c // 2 comparisons
else if(a<c) // a,c,b // 3 comparisons
else // c,a,b // 3 comparisons
else
if( (a<c) // b,a,c // 2 comparisons
else if(b<c) // b,c,a // 3 comparisons
else // c,b,a // 3 comparisons
Thus, in 4 out of 6 possible cases we need 3 rather than 2 comparisons.
Not intended as an answer, but as an illustration of the comment by Sam Varshavchik:
What's wrong is that the code should use a small array, and std::sort,
instead of this kind of spaghetti code.
While Sam is right about production code, as an exercise of how to implement the logic, the question is okay and there is already a solution.
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v(3);
if (! (std::cin >> v[0] >> v[1] >> v[2])) { exit(-1); }
std::sort(v.begin(), v.end(), std::greater<int>());
for (auto c: v) { std::cout << c << " "; }
std::cout << "\n";
}
I have this code
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
double log2x;
double logx;
int main()
{
std::cout << std::setprecision(6) << std::fixed;
int lines;
cout << "How many lines would you like to calculate? " << endl;
cin >> lines;
cout << "x " << " log10x " << " log2x " << "logx " << endl;
cout << "-------------------------------------------------------" << endl;
int stepcount = 1;
int exponentstep = 0;
int logvariable;
for (int i = 0 ; i < lines; i++)
{
logvariable = stepcount * pow(10,exponentstep);
log10x = log10(logvariable);
log2x = log2(logvariable);
logx = log(logvariable);
stepcount++;
while (stepcount == 10)
{
stepcount = 1;
exponentstep++;
}
cout << left << setw(10) << logvariable << left << " " << setw(10) << log10x << " " << setw(10) << log2x << " " << setw(10) << logx << endl;
}
return 0;
}
it outputs the natural log functions for values 1-9 * 10^n, so
1 2 3 4 5 6 7 8 9 10 20 30 40 50 60 70 80 90 100 200 etc. I was pretty convinced what i had would work, but my codeblocks would give 10 correct answers and then 10 that were off by one. I tried cpp.sh and it worked beautifully. Not sure why at all? I couldn't get it to compile in visual studios at all and i didn't get a useful enough error message to figure it out. Any reason why codeblocks would mess up code that appears to be working otherwise? Thanks so much.
double log2x;
double logx;
//You forgot to declare log10x
double log10x;
You should copy the code into a text document and create a new project. Once you created a new project go to "view" then manager or shift+f2 and you should see your project. Make sure that the main.cpp is in the "Sources"under your project and paste the code, save it and compile it.
Everything worked for me and it looked like the correct answers once I declared the log10x so try to make a new project and if that doesn't help I believe your creating codeBlock projects incorrectly and I can walk you through it, its very simple.
I am writing a program to create a horizontal histogram from an array of type double data. I was able to get the program to display the boundaries of each sub-interval along with the correct number of asterisks. However, the data is not formatted.
Here's the part of the program responsible for the output:
// endpoints == the boundaries of each sub-interval
// frequency == the number of values which occur in a given sub-interval
for (int i = 0; i < count - 1; i++)
{
cout << setprecision(2) << fixed;
cout << endPoints[i] << " to " << endPoints[i + 1] << ": ";
for (int j = frequency[i]; j > 0; j--)
{
cout << "*";
}
cout << " (" << frequency[i] << ")" << endl;
}
Here's what my output looks like:
0.00 to 3.90: *** (3)
3.90 to 7.80: * (1)
7.80 to 11.70: * (1)
11.70 to 15.60: (0)
15.60 to 19.50: ***** (5)
Here's what I would like it to look like:
00.00 to 04.00: *** (3)
04.00 to 08.00: * (1)
08.00 to 12.00: * (1)
12.00 to 16.00: (0)
16.00 to 20.00: ****** (6)
I've looked up C++ syntax and have found things like setw() and setprecision(). I tried to use both to format my histogram but have not been able to make it look like the model. I was hoping someone could tell me if I'm on the right track and, if so, how to implement setw() and/or setprecision() to properly format my histogram.
Assuming that all numbers are in the [0,100) interval, what you want is a chain of manipulators like:
#include <iostream>
#include <iomanip>
int main() {
std::cout
<< std::setfill('0') << std::setw(5)
<< std::setprecision(2) << std::fixed
<< 2.0
<< std::endl;
return 0;
}
Which will output:
02.00
This is for a single value, you can easily adapt it to suit your needs.
You could, for instance, turn this into an operator and use it like:
#include <iostream>
#include <iomanip>
class FixedDouble {
public:
FixedDouble(double v): value(v) {}
const double value;
}
std::ostream & operator<< (std::ostream & stream, const FixedDouble &number) {
stream
<< std::setfill('0') << std::setw(5)
<< std::setprecision(2) << std::fixed
<< number.value
<< std::endl;
return stream;
}
int main() {
//...
for (int i = 0; i < count - 1; i++) {
std::cout
<< FixedDouble(endPoints[i])
<< " to "
<< FixedDouble(endPoints[i + 1])
<< ": ";
}
for (int j = frequency[i]; j > 0; j--) {
std::cout << "*";
}
std::cout << " (" << frequency[i] << ")" << std::endl;
//...
}
I want to print the first 2 values where the next is doubled from the current value.
#include <iostream>
#include <deque>
#include <algorithm>
using namespace std;
bool doubled (int x, int y) { return x*2 == y; }
int main()
{
deque<int> di;
deque<int>::iterator diiter;
for (int i=0; i<=10; i+=2) di.insert(di.end(), i);
for (diiter = di.begin(); diiter != di.end(); ++diiter)
cout << *diiter << " ";
cout << endl;
diiter = adjacent_find(di.begin(), di.end(), doubled);
if (diiter != di.end()) {
cout << "found " << *diiter << " at " << distance(di.begin(), diiter)+1
<< " and " << *(++diiter) << " at " << distance(di.begin(), diiter)+1
<< endl;
}
}
the output is
0 2 4 6 8 10
found 4 at 3 and 4 at 2
not what I expected, which should be:
0 2 4 6 8 10
found 2 at 2 and 4 at 3
What's wrong with my code? I don't understand how the second position is decremented from the first one when I actually incremented it.
Thanks for all help.
Your program is giving strange results because it does not take in to account the fact, that order of evaluation of arguments to a function(In this case operator <<) is Unspecified.
My Answer here, explains the problem in detail & should be a good read.
You need to cout them on separate statements.
cout << "found " << *diiter;
cout << " at " << distance(di.begin(), diiter)+1;
cout << " and " << *(++diiter);
cout << " at " << distance(di.begin(), diiter)+1;
cout << endl;
This works well & outputs the correct/desired output.