#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int riceamount=2,
squarenumber=1,
totalamount=0,
neededrice1000=0,
neededrice1000000=0,
neededrice1000000000=0;
cout<<"Amount of rice you need for the square "<<
squarenumber<<" is " <<riceamount-1<<endl;
cout<<"Amount of rice you need for the square "<<
squarenumber+1<<" is " <<riceamount<<endl;
squarenumber=2;
for(int i=2;i<65;i++)
{
riceamount=riceamount*2;
++squarenumber;
cout<<"Amount of rice you need for the square "<< squarenumber<<" is " <<riceamount<<endl;
totalamount=totalamount+ riceamount;
if (totalamount>1000)
squarenumber=neededrice1000;
if (totalamount>10000000 && totalamount<1100000)
squarenumber=neededrice1000000;
if (totalamount>1000000000 && totalamount<1100000000)
squarenumber=neededrice1000000000;
}
system("pause");
return 0;}
When I debug Command window print numbers weirdly(after 10 it weirdly turn back to 1 and keep going printing 1 as squarenumber then continue from 2 when c++ gave up calculating powers), as you can see below from image, why? Thanks for any help. Command window picture
after 10 it weirdly turn back to 1 and keep going printing 1 as squarenumber
You told it to:
if (totalamount>1000)
squarenumber=neededrice1000;
This has nothing to do with the Visual Studio command window; it is the stated logic of your program.
I suggest you step through it, line by line, using pencil and paper, so that you understand what you have written.
when c++ gave up calculating powers
It didn't "give up"; you overflowed your int with huge numbers, so your program has undefined behaviour.
For you, this resulted in low values, low enough that the previously pointed-out bug no longer kicks in, and squarenumber is once again free to increment on each iteration.
In this example, a 64-bit type will be enough (so consider uint64_t).
Eventually riceamount * 2 overflows the int type.
The behaviour on doing that is undefined, but in your case the computation is effectively modulo a power of 2, which is zero for a large power of 2.
An unsigned long long would be big enough for the total number of grains of rice distributed across 64 squares with 1 grain on the first square.
Related
I'm trying to write a program to check if a number between 1 and 9999999 is a number whose digits either stay the same or increases from left to right(The variable and function names are in Vietnamese)
#include<stdio.h>
int daykhonggiam(int n)
{
while (n>=10)
{
int donvi=n%10;
n=n/10;
if(donvi<n%10)
{
return 0;
}
}
return 1;
}
int main(void)
{
for(int i=1;i<=9999999;i++)
{
if(daykhonggiam(i)==1)
printf("%d\n",i);
}
}
The problem is, when i compile and run the code ,only some of the results were shown( the results from 5555999 to 9999999 ). when i hit f9 i can the the results run from 1 but the final screen only shows from 5555999 to 9999999. I tried an online compiler and all the results were shown.
So i guessing my dev c++ 5.11 is the problem here. Is there any chance any of you know why that's the case ?
It looks like printf just fills console buffer completely and old lines get removed. Try writing results to file or increase console buffer capacity somehow.
Open your terminal, click the top left corner, go to properties, and increase your buffer size. Save, and test. Repeat if needed.
That being said, I concur with previous comments that you should just use an output file.
Edit: After some testing, I could only get a max number of 9,000 lines to display concurrently. I'd pursue using an output file in your case.
I keep getting wrong outcome, while I try to sum big arrays. I have isolated problem to the following code sample (its not an sum of a big array, but I believe this is The problem)
Compilable Sample:
template <typename T>
void cpu_sum(const unsigned int size, T & od_value) {
od_value = 0;
for (unsigned int i = 0; i < size; i++) {
od_value += 1;
}
}
int main() {
typedef float Data;
const unsigned int size = 800000000;
Data sum;
cpu_sum(size, sum);
cout << setprecision(35) << sum << endl; // prints: 16777216 // ERROR !!!
getchar();
}
Environment:
OS: Windows 8.1 x64 home
IDE: Microsoft Visual Studio 2015
Error Description:
While my outcome should obviously be sum == 800000000 I keep getting sum == 16777216.
That is very weird for me, because float max value is far above this one, and yet it looks like sum variable reach its limit.
What did I miss??
It is a well known problem. Gradually your sum becomes so big that next summand becomes comparable with an epsilon (about 10^-14) of it. At that moment you start loosing precision.
Standard solution is to change summation tactics: when array larger than, say, 100 elements, split it in halves and sum each half separately. It goes on recursively and tend to keep precision much better.
As pointed out by Michael Simbursky, this is a well-known problem when trying to sum a large number of limited-precision numbers. The solution he provides works well, and is quite efficient.
For the curious reader, a slower method is to sort your array before computing the sum, assuring that the values are added in order of increasing absolute value. This ensures that the least-significant values make their contributions to the overall sum before being overwhelmed by the other values. This technique is used more as an example/illustration than in any serious programming ventures.
For serious scientific programming where the overall size of the data can vary a great deal, another algorithm to be aware of is the Kahan Summation Algorithm, and the referenced wikipedia page provides a nice description of it.
so I'm trying to write a guess the number game in C++.The computer is Supposed to take a random number with 4 digits then the player should enter a number too.Rules are:
if the computer chooses:1234
And the player enters:1356
1 must be displayed in green,3 must in yellow since it's in the wrong place and 5&6 in red.the game goes on till the player gets the right answer.
#include<iostream>
#include <windows.h>
#include <stdlib.h>
#include <time.h>
#include<unistd.h>
using namespace std;
int main()
{
int b;
HANDLE handle=GetStdHandle(STD_OUTPUT_HANDLE);
cout<<"System is now generating a number...."<<"\n";
int *Number = new int[4];
srand (time(NULL));
for(int counter=0;counter<4;)
{
Number[counter]=(rand()%9)+1;
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
{
counter ++;
}
else
{
counter--;
}
}
cout<<Number[0]<<Number[1]<<Number[2]<<Number[3]<<"\n";
int *Guess=new int[4];
cout<<"please enter 4 digits for your number"<<"\n";
for(int counterG=0;counterG<4;counterG++) //line 34
{
cin>>Guess[counterG];
for(int counter;counter<4&counter>0;)
{
if((counter=counterG)&(Guess[counterG]=Number[counter])) //line 40
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,10);
cout<<b<<"\n";
}
if((counter=counterG)&(Guess[counterG]==Number[counter- 1]|Guess[counterG]==Number[counter+1]|Guess[counterG]==Number[counter-2]|Guess[counterG]==Number[counter+2]))
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,14);
cout<<b<<"\n";
}
else
{
b=Guess[counterG];
SetConsoleTextAttribute(handle,12);
cout<<b<<"\n";
}
}
}
now the program is fine until line 34 but nothing happens after that!
It just gets the player digits
I'd be glad if you could tell me what I've done wrong
Not a complete answer, but it's too long for a comment:
if(Number[counter]!=Number[counter-1]&Number[counter]!=Number[counter-2]
2]&Number[counter]!=Number[counter-3])
This line alone contains a lot of errors:
To have the logical AND operator you need &&, not &.
You have typed an extra 2] at the beginning of the second line. I hope it's just a typo that you introduced when writing the question.
The first time you run this, counter is 0. What happens when you try to access Number[counter-3]? It's an out of bounds access, which leads to Undefined Behaviour, which can lead to anything.
And there are probably many more.
What to do now:
Work on your code indentation. It's really bad.
Start from a much simpler program, and verify that it works. Then, add one small step, verify it, and don't move on until you are happy with the result
Turn on your compiler warnings. Warnings are your friends, not a boring annoyance
Learn how to use a debugger. You won't go very far without debugging.
1- replace & with &&(AND operator)
2- take input in a simple integer variable and then validate the number by performing first check of number greater than 0 and less than 9999.
3- then seperate digits from this variable and then assign those digits to aaray indexes respectvely.
I've written a simple code to practice some stuff, but it's not running as it's supposed to.
I'm programming on my iPhone just for fun and l'm using an app called c/c++ offline compiler which seems to work really well.
Anyway, I wrote a program to display numbers, and if the number is less than 5 digits, in each empty space display a star. Then next to that, display the memory address.
There are two questions I have. First, why are the stars not displaying when I run this. Second, each time run it, the memory addresses are different. Is this because of the compiler, or because of how the iPhone's memory works?
Source Code:
//c plus plus program 1
#include <iostream>
using namespace std;
int main (void){
for(int i=0; i<150;i+=30){
cout.width(5);
cout.fill('*');
cout<<i<< "="<<&i <<endl;
}
return 0;
}
It is normal that address of i is changing each time you run your program. As I know it is because of how system works with memory. Why did you think it will place your program in the same part every time? :-)
I tried you code in http://cpp.sh only and stars were shown:
****0=0xffcde9dc
***30=0xffcde9dc
***60=0xffcde9dc
***90=0xffcde9dc
**120=0xffcde9dc
Note, that all after second << was not took into consideration when output width was determined. So first of all to investigate the problem I would try something like
int main (void) {
cout.width(5);
cout.fill('*');
cout << 1 << endl;
cout << 2 << endl;
}
to understand if it compiler problem or not.
#include<iostream>
using namespace std;
int main(){
int i,x,max=0;
cin>>x;
int a[x];
for(i=0;i<x;i++){
cin>>a[i];
if(max<a[i]){
max=a[i];}
}
int b[max+1];
for(i=0;i<max+1;i++){
b[i]=-1;
}
for(i=0;i<x;i++){
if(b[a[i]]==-1){
b[a[i]]=1;
}
else{
b[a[i]]++;
}
}
i=0;
while(i<=max){
while(b[i]>0&&b[i]!=-1){
cout<<i<<endl;
b[i]--;
}
i++;
}
return 0;
}
Guys I tried indexing method for sorting and codechef shows tle .. complexity of this problem is not o(n) but closer to it ... the question has a time limit of 5 sec and source limit is 50000 bytes..
Any help on how to improve the performance either by faster i/o or code computations ...
I'm pretty certain your code is problematic because you are using cout << x << endl; in a loop that will print a huge number of lines.
I will be back with "difference" in a few minutes.
Edit: Not sure I can make much of a difference either way. Obviously, depending on compiler, it may vary greatly, but with my g++ -O2 and 100000 input numbers, it takes 0.16 - 0.18s to use endl; and 0.06 - 0.07s to use '\n' for the output.
Using printf isn't faster than cout, but scanf is a little faster than cin (0.04s +/- 0.05).
However, that is really related to sync_with_stdio. If we use cin.sync_with_stdio(false); then the results are the same for scanf and cin.
All measurements are made with a file as input and a file as output - it takes much longer to write to the shell, but that's because it's scrolling 100k lines of text past me.
(Your program will crash with eithr "large" inputs or with large number of inputs - if max is greater than about 1 million, the code will crash due to out of stack - on many systems, that may happen for lower values too)
Avoid cin and cout, and use the C IO functions scanf and printf instead. You'll find they can be up to 5x faster than the slow c++ functions.