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.
Related
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!
That's my first question here, so I would be glad to receive some support on the style I used to refer to my problem :). Here is the finished program, its main purpose is to split given words into halves and create words replacing the origin ones. Replaced words are build from its origins by spliting them into halves and taking even ones from the 1st half begining with the first letter of a word. Heres the complete code:
#include <iostream>
#include <string>
#include <cstdio>
#include <math.h>
using namespace std;
void obcinaczSlow(int);
int main(){
int ilosc;
cout << "Prosze o podanie ilosci prob: ";
cin>>ilosc;
cout << endl;
obcinaczSlow(ilosc);
cin.ignore();
cin.get();
return 0;
}
void obcinaczSlow(int ilosc_prob){
int i=0,j=0,dlugosc_slowa=0,dlugosc_polowy=0;
string *tablica_slow,budowane_slowo,aktualne_slowo,dodane;
tablica_slow = new string [ilosc_prob];
cout << "Prosze o podanie " << ilosc_prob << " slow" << endl;
cin.sync();
for(i=0;i<ilosc_prob;i++){
cout << "Prosze o podanie slowa numer: " << i+1 << endl;
cin>>aktualne_slowo;
tablica_slow[i] = aktualne_slowo;
}
for(i=0;i<ilosc_prob;i++){
aktualne_slowo = tablica_slow[i];
cout << "Aktualne slowo do przerobienia: " << aktualne_slowo << endl;
dlugosc_slowa = aktualne_slowo.length();
cout << "Dlugosc slowa do przerobienia: " << dlugosc_slowa << endl;
dlugosc_polowy = floor(dlugosc_slowa/2);
cout << "Dlugosc polowy slowa int: " << dlugosc_polowy << endl;
budowane_slowo.clear();
dodane.clear();
cout << "Budowane slowo to: " << budowane_slowo << endl;
for(j=0;j<=dlugosc_polowy;j=+2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}
tablica_slow[i] = budowane_slowo;
}
cout << "Slowa po transformacji wygladaja nastepujaco: " << endl;
for(i=0;i<ilosc_prob;i++){
cout << "Slowo o numerze " << i+1 << " : " << tablica_slow[i] << endl;
}
delete [] tablica_slow;
cin.sync();
}
The problem raises when program reaches the loop, that is supposed to append the letter pointed by the j-index using '.at' method from the string class. I can't find a solution even trying to debug it. Could You help me :)?
You have a typo here
for(j=0;j<=dlugosc_polowy;j=+2)
I assume you meant += instead of =+
for(j=0;j<=dlugosc_polowy;j+=2)
Otherwise you are just assigning 2 to j over and over again.
Your error is reversing two characters:
Change:
`j=+2` to `j+=2`
^^ ^^
(The way it is written j is assigned the value of 2, then, for the rest of its life, stays there.)
for(j=0;j<=dlugosc_polowy;j=+2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}
replace the j=+2 to j+=2
for(j=0;j<=dlugosc_polowy;j+=2){
dodane = aktualne_slowo.at(j);
budowane_slowo.append(dodane);
}
Let me preface this by saying I'm still extremely new to C++ and want to keep things as simple as possible. I'm also pretty terrible at math.
Mostly, I'm looking to see if anyone can help my code so it will always give the correct result. I've mostly got it to do what I want, except in one scenario.
My code is trying to find out how many packages of hotdog weiners and how many packages of hotdog buns someone has purchased. Then it tells the user how many hotdogs they can make from that as well as how much leftover weiners or buns they would have. Assuming a package of weiners contains 12 and a package of buns contains 8, this is what I have come up with so far:
#include <iostream>
#include <cmath>
using namespace std;
void hotdog(int a, int b){ //a = weiner packages, b = bun packages
int weiners = 12 * a;
int buns = 8 * b;
int total = (weiners + buns) - (weiners - buns);
int leftOverWeiners = total % weiners;
int leftOverBuns = total % buns;
int totalHotDogs = total / 2;
cout << "You can make " << totalHotDogs << " hotdogs!" << endl;
if (leftOverWeiners > 0){
cout << "You have " << leftOverWeiners << " weiners left over though." << endl;
}else if (leftOverBuns > 0){
cout << "You have " << leftOverBuns << " buns left over though." << endl;
}
}
int main(){
int a;
int b;
cout << "Let's see how many hotdogs you can make!" << endl;
cout << "How many weiner packages did you purchase?: ";
cin >> a;
cout << "How many bun packages did you purchase?: ";
cin >> b;
hotdog(a, b);
return 0;
}
With this, I can always get the correct answer if the ratio of buns to weiners is the same or if there are more weiners than buns.
Because of the way I've set up total and/or leftOverBuns (lines 9, 11), I will never get the correct answer to how many left over buns there will be. I know there must be a simpler way to do this if not a way to modify my current code but I am stumped.
I know I left virtually zero notation, so if you would like some please let me know!
You're making it too complicated. Try this:
if(weiners > buns)
{
cout << "You can make " << buns << " hotdogs!" << endl;
cout << "with " << weiners-buns << " weiners left over" << endl;
return;
}
cout << "You can make " << weiners << " hotdogs!" << endl;
if(buns > weiners)
{
cout << "with " << buns-weiners << " buns left over" << endl;
}
The smaller of {buns, weiners} is the number of hot dogs, and the if-then blocks determine whether the function will report leftover buns or weiners.
#include <iostream>
void hotdog( int weinerspackages, int bunspackages ){
const int weinersPerPackage = 12;
const int bunsPerPackage = 8;
const int totalweiners = weinerspackages * weinersPerPackage;
const int totalbuns = bunspackages * bunsPerPackage;
int leftoverweiners = 0;
int leftoverbuns = 0;
int amountOfHotdogs = 0;
if( totalweiners > totalbuns ){
leftoverweiners = totalweiners - totalbuns;
amountOfHotdogs = totalbuns;
leftoverbuns = 0;
}
else if( totalbuns > totalweiners ){
leftoverbuns = totalbuns - totalweiners;
amountOfHotdogs = totalweiners;
leftoverweiners = 0;
}
else{
amountOfHotdogs = totalweiners;
leftoverweiners = 0;
leftoverbuns = 0;
}
std::cout << "You can make: " << amountOfHotdogs << " Hotdogs" << std::endl;
std::cout << "Leftover Weiners: " << leftoverweiners << " || Leftover Buns: " << leftoverbuns << std::endl;
}
int main(){
int PackagesW = 8;
int PackagesB = 12;
hotdog( PackagesW, PackagesB );
system("pause");
return 0;
}
Note: It is possible to do this with less variables, I declared this amount of variables to make it easier to understand what the numbers represent.
Assuming that it only takes one of each to make a hotdog, you can find which of the ingredients you have the least, and the amount of hotdogs you can make will be limited by the amount of that ingredient, that is why amountOfHotdogs takes the value of the lesser one. If both are equal in amount, then amountOfHotdogs can take the amount of either.
Only the ingredient with the larger amount will have leftovers, therefore leftoverweiners = totalweiners - totalbuns; when totalweiners > totalbuns and vice-versa.
I've been having a slight issue with my program, what I'm trying to do is develop a way for users to simulate the possible strengths of passwords. This is assuming that all passwords are permutations (weird I know, but I presume that this is to stop data from becoming even more unwieldy.) using the equation...
//n!/(n-r)! when n! = (e^-n)*(n^n) sqrt(2(pi)n). When n is number of characters in use and r is length of password
No matter what I put I receive nan as an answer. I thought that perhaps my equation was off (maybe somehow I was dividing by zero) so I reworked it and simplified it a great deal. But that didn't seem to be the problem, though I feel that this got me closer to being correct. But I had the thought that maybe numeric overflow is having an effect here? But I really don't know how to fix something like that. I tried jumping from different data types but nothing seemed to work.
I have a problem with the modulus too. It returns back numbers less than zero for time, so with my noobish knowledge that tells me that maybe I'm overflowing it again but how else am I going to use % without defining it as an int? Maybe fixing the above problem will work out this one?
I would be beyond grateful for any help given to me. How does one go about dealing with return values of nan? Is there a step by step status quo for solving it? Is it pretty much always overflow or could it be something else?
The code itself.
#include <iostream>
#include <cmath>
using namespace std;
const int SECONDS_IN_YEAR = 31556926;
const int SECONDS_IN_DAY = 86400;
const int SECONDS_IN_HOUR = 3600;
const int SECONDS_IN_MIN = 60;
int main()
{
int passwordLength ,characterSymbols;
double instructionsPerSecond, instructionSuccess;
////////////////////////////////////////////////////////////////////////////////
//Equations needed
// n!/(n-r)!
//n is the number of letters in the alphabet
//and r is the number of letters in the password
// n! = (e^-n)*(n^n) sqrt(2(pi)n)
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
// (n-r)
double characterMinusLength= (characterSymbols-passwordLength);
// (n-r)! = (e^-(n-r)) * ((n-r)^(n-r)) * sqrt(2(pi)(n-r))
double denominatorFactorial = ((pow(M_E, -(characterMinusLength)))*
(pow((characterMinusLength),(characterMinusLength)))
* (sqrt(2*M_PI*(characterMinusLength))));
// n!/(n-r)!
long double passwordPermutation = (numeratorFactorial / denominatorFactorial);
// (passwords)* (instructions/Password) * (seconds/instruction) = sec
int passwordSeconds = (passwordPermutation * instructionSuccess)
*(1/instructionsPerSecond);
int passwordMin = passwordSeconds / SECONDS_IN_MIN ;
int passwordHour = passwordSeconds / SECONDS_IN_HOUR;
int passwordDay = passwordSeconds / SECONDS_IN_DAY ;
int passwordYear = passwordSeconds / SECONDS_IN_YEAR;
////////////////////////////////////////////////////////////////////////////////
//Explain purpose of program
cout << "This program is designed to simulate the strength of passwords." << endl;
//Ask for alphabet
cout << "But first, share with me the max number of characters you'd be using."
<< endl;
cin >> characterSymbols;
//Reflect information
cout << "We will be using " << characterSymbols << " character symbols to "
<< " construct the password.\n" << endl;
///////////////////////////////////////////////////////////////////////////////
//Input length of password
cout << "\n\nWill you give me the length of proposed password?" << endl;
cin >> passwordLength;
//Repeat information
cout << "The password length will be " << passwordLength << "." <<endl;
//cout permutations
cout << "This would lead to " << passwordPermutation << " unique password\n"
<< endl;
////////////////////////////////////////////////////////////////////////////////
//Ask for computer strength
cout << "How powerful is this computer? How many instructions per second " << endl;
cout << "can it accomplish?" << endl;
cin >> instructionsPerSecond;
//Read out computer strength
cout << "The computer can do " << instructionsPerSecond << " instructions/second"
<< endl << endl;
////////////////////////////////////////////////////////////////////////////////
//Ask for instructions/password
cout << "The number of instructions needed to test your password is." << endl
<< endl;
cin >> instructionSuccess;
//reflect
cout << "This computer can do " << instructionSuccess
<< " instructions/password" << endl;
////////////////////////////////////////////////////////////////////////////////
cout << "\n\nThe amount of seconds it'll take to crack this passcode is... "
<< endl << passwordSeconds << " seconds.\n\n\n\n\n" << endl;
////////////////////////////////////////////////////////////////////////////////
//Reflect all information in an easily readable table
cout << "Number of character symbols using... " << characterSymbols << endl;
cout << "Length of password... " << passwordLength << endl;
cout << "Number of permutations... " << passwordPermutation << endl;
cout << "Instructions per second... " << instructionsPerSecond << endl;
cout << "Instructions per password..." << instructionSuccess << endl;
cout << endl << endl << endl;
////////////////////////////////////////////////////////////////////////////////
//Add in conversions for min, hour, day, years
cout << "Number of seconds to break..." << passwordSeconds << endl;
cout << "Converted to minutes..." << passwordMin << endl;
passwordMin = passwordSeconds / SECONDS_IN_MIN;
passwordSeconds = passwordSeconds % SECONDS_IN_MIN;
cout << "Converted to hours..." << passwordHour << endl;
passwordHour = passwordSeconds / SECONDS_IN_HOUR;
passwordSeconds = passwordSeconds % SECONDS_IN_MIN;
cout << "Converted to days..." << passwordDay << endl;
passwordDay = passwordSeconds / SECONDS_IN_DAY;
passwordSeconds = passwordSeconds % SECONDS_IN_DAY;
cout << "Converted to years..." << passwordYear << endl;
passwordYear = passwordSeconds / SECONDS_IN_YEAR;
passwordSeconds = passwordSeconds % SECONDS_IN_YEAR;
return (0);
}
"nan" stands for "not a number". This is happening because you have declared the variables characterSymbols and passwordLength without giving them an initial value.
You must initialize any variable before you use it - if you don't then you will have undetermined behavior. For example:
int x;
int y;
int z = x + y;
There is no way to predict what z will be equal to here because we don't know what x or y are equal to. In the same way, your code should be something like:
int characterSymbols = 10; //or whatever you want the initial value to be
...
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
In this way, numeratorFactorial will have a valid value.
It appears you think you are declaring "equations" when you are actually declaring variables. You write:
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
But characterSymbols isn't defined, only "declared". characterSymbols is declared above it, but it doesn't have a value... yet. Later on you use cin to get a value into it, but when you first declare numeratorFactorial you can't simply expect the program to insert the value into numeratorFactorial when characterSymbols changes.
Some definitions are probably in order: The statement double numeratorFactorial = some_value; creates a variable named numeratorFactorial and uses some_value to fill that variable immediately. What you want is a function, a logical statement that you can "pass values" to so values are generated when you need them. For example, for your numerator factorial:
double numeratorFactorial(double characterSymbols) {
return (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
}
int main() {
std::cout << "Numerator Factorial test: " << numeratorFactorial(5.0) << std::endl;
}
Note that you cannot declare a function within the main function.
This sort of thing is programming fundamentals, and it seems like you are trying to run before you've learned to walk. Get a good book like C++ Primer and pace yourself.
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.