Changing variables during if-else if- else statements in C++ - c++

As I'm sure the question makes clear, I'm new and learning and I'm sure many will wonder why ask.....cause I get the rest of it, just not this. I am using C++ and am trying to make a self guessing program, that uses an algorithim given to me. I have played with this section of code multiple ways and so far the one thing I have narrowed down, is what its not doing, and I want to both understand why and how to fix it because nothing I have tried is working. The basic version of the code I have been playing with is this:
// test_room.cpp : This file contains the 'main' function. Program execution
//begins and ends there. This is where
//I am going to test some code to understand my mistakes and how to fix
//them.
//
#include "pch.h"
#include <iostream>
#include <cstdlib>
#include<ctime>
using namespace std;
int main()
{
char play = 'y';
while (play == 'y')
{
int bad = 27;
int a = 50;
int b = 1;
int good = ((a - b) / 2);
int s = 0;
cout << "\nBegin?";
cin >> play;
do
{
++s;
if (good > bad)
{
cout <<"\n" <<good;
cout <<"\n" << s;
--a;
}
else if (good < bad)
{
cout << "\n"<<good;
cout <<"\n" << s;
++b;
}
else
{
cout << "good job";
}
} while (s < 50);
}
cout << "\nOK\n";
return 0;
}
What my question is I have tried moving the variables, I have fixed brace issues, I have tried using cin>>good>>a or b(depending on >< ) and so far I can not manipulate variables a or b to get it to try to guess or figure out the number 27, all it does is repeat 24 50 times. What do I need to do to change the values of a and b based on the algorithim?

Good and bad are never changed in the loop, I don't really understand the purpose of you algorithm(it looks like a binary search, but not really), but if you aren't changing any values that the if conditions evaluate in the loop, then none of the other conditions will ever be evaluated.

Related

Nesting int main() inside int main()

I am trying to make the simplest of all games, but with a loop function.
I'm given the error "a function-definition is not allowed here before '{', as well as a whole list of [Error] expected '}' at end of input.
Am I not allowed to nest int main() within another? Is that my issue at all? How do I accomplish this code without the nesting?
My knowledge and experience extend no more than a few chapters in two books.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char again = 'y';
while (again == 'y')
int main()
{
srand(static_cast<unsigned int>(time (0)));
int secret = rand() % 100 +1;
int tries = 0;
int guess;
cout << "\tGuess the random number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++ tries;
if (guess > secret)
{
cout << "Too High!\n\n:";
}
else if (guess < secret)
{
cout << "Too Low!\n\n";
}
else
{
cout << "\nThat's It! You go it in " << tries << " guesses!\n";
}
} while (guess != secret);
}
cout << "\n\tWould you like to play again? (y/n): ";
char again;
cin >> again;
}
Your issue is nesting a main function inside of the existing main function. (This is not allowed.) In general, (With the exception of some stuff you can do with structs/lambdas which approximate that kind of functionality) you shouldn't nest functions inside of each-other. If you merely remove the function declaration, then your code should work fine:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
char again = 'y';
while (again == 'y')
{
srand(static_cast<unsigned int>(time (0)));
int secret = rand() % 100 +1;
int tries = 0;
int guess;
cout << "\tGuess the random number\n\n";
do
{
cout << "Enter a guess: ";
cin >> guess;
++ tries;
if (guess > secret)
{
cout << "Too High!\n\n:";
}
else if (guess < secret)
{
cout << "Too Low!\n\n";
}
else
{
cout << "\nThat's It! You go it in " << tries << " guesses!\n";
}
} while (guess != secret);
cout << "\n\tWould you like to play again? (y/n): ";
cin >> again;
}
}
As far as I know, you cannot nest int main() inside of int main() for a number of reasons. In general, you can't define one function inside of another (defining "locally"). However, even if you can, your desire to do so should be a massive red flag that your design is off.
NOTE: As Nathan Oliver pointed out in the comments, you can forward-declare a function "locally" (within another function), but the actual implementation must be outside. Even doing this, you should usually second-guess your design at this point.
You need to be asking yourself what you're trying to do.
Are you wanting to group code together under a function to call repeatedly? Then create a separate function (with a different name) outside of main().
Are you wanting to repeat code? If so, you need a loop or a recursive function structure.
Are you wanting to split up some behavior into several functions, but hide all but one function involved? If so, look into classes (not necessarily objects - you can also have static classes.)
Those are just three of many possibilities, and deciding exactly what you want to do and how you want to do it is your responsibility alone to decide, as a programmer.
Brief recap: as far as C++ (and C) are concerned, if you're trying to declare any function inside any other function, you are doing something seriously wrong in design.
On a more technical note, you should also understand precisely what int main() is. It is a special function that is the entry point for your program. No C or C++ program can run without an int main().
You have to have a single instance of this function in main.cpp in order for your program to work. If you have more than one int main(), the computer cannot likely will not be able to find the entry point.
Besides that, having more than one function called main() anywhere in your code is a great way to confuse yourself and others.
In short, you should only have one int main() per program, no exceptions.

C++ cout won't work inside for and if?

I have those two pieces of code as my home assignment. The code looks all fine to me, but it won't print out what I want, no matter what. In fact, the console output remains completely empty.
The first program is supposed to print out all numbers that fulfil the ladna() function requirements and are between 1 and a:
#include <iostream>
using namespace std;
int a;
int i = 1;
bool ladna(int a)
{
if((((a>>4)*5+a*2)%3)==1)
return true;
else
return false;
}
int main()
{
cerr << "Podaj liczbe: " << endl;
cin >> a;
while (i <= a){
if (ladna(a)){
cout << i << " ";
}
i++;
}
}
the ladna() function is premade and I have to use it as is.
I tried changing while into do...while and for, didn't help. Doesn;t work with cerr either.
The second code has to print out all the natural divisors of number a.
#include <iostream>
using namespace std;
int main()
{
int a;
cerr << "Podaj liczbe" << endl;
cin >> a;
for (int i = 0; i >= a; i++){
if (a % i == 0){
cout << i << endl;
}
}
return 0;
}
Doesn't work either.
To me it looks like both pieces of code have the same issue, because they are written in the same way, based on the same principle, and the error is the same. Hence my assumption, that the cause is the same as well.
Unfortunately, for the love of me, I simply can't see what said error is...
For the first code:
I think you should call ladna function with i, like ladna(i)
For the second code:
In for it should be i<=a
'%' is the modulo operator, during the execution of (a%i) you divide a with i and take the remainder, since i start with zero you will get "Floating point exception (core dumped)" due to division by zero. So, for should start with 1. This should work:
for (int i = 1; i <= a; i++){
if (a%i == 0){
cout << i << endl;
}
}

What causes a runtime error in this code

I'm working on the UVA problem 12468 Zapping.
I've checked several test cases and it works successfully but when I submit this solution to UVA online judge it judged it as runtime error. Where can the error be? Please explain your answer.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int a,b,next,bk;
while(true)
{
cin >> a >> b;
if (a == -1 && b == -1)
break;
next = abs(a - b);
if (next > 50)
{
bk = (a % b) + 1;
cout << bk << endl;
}
else
{
cout << next << endl;
}
}
return 0;
}
Your question in essence is "how can the following code cause a run time error". The answer to that question is given by πάντα ῥεῖ, and it happens on line (a%b)+1 when variable b is equal to zero.
But if the actual question is "how to change the code so that it gives the correct output according to problem 12468 description" then the answer should be to replace that line with the following:
bk = 100 - next;
So if zapping the remote in one direction takes more than half of the maximum this tells you how much will it take zapping it in the opposite direction.

How to output a certain piece of an array using a variable C++

I want to have an array output a certain piece of the array depending on what a randomly generated variable is.
I want to have a karate-based simulator that reads what the opponent's kick is (1, 2, 3, or 4,) and connects that with certain kicks. (Round Kick, Hook Kick, Front Kick, Side Kick) and then prints that to the screen.
Skip to int main() if you need to, the rest of the code is for reference.
My code:
#include <iostream>
#include <random>
#include <ctime>
#include <string>
#include <Windows.h>
using namespace std;
mt19937 ranGen(time(0));
uniform_real_distribution<float> attack(0.00f, 1.00f);
uniform_real_distribution<float> defense(0.00f, 1.00f);
uniform_int_distribution<int> okick(1, 4);
string belt = "White Belt";
float landed = attack(ranGen);
float blocked = defense(ranGen);
float ekick = okick(ranGen);
int kick;
string kicks [4] = ("Round Kick","Hook Kick","Front Kick","Side Kick");
void roundKick() {
if (belt == "White Belt") {
if (landed < 0.70) {
cout << "Round kick to head | Blocked\n";
} else {
cout << "Round kick to head | Direct Hit\n";
}
}
}
int main()
{
string yn;
syn:
cout << "Spar? y/n\n";
cin >> yn;
if (yn == "y") {
cout << "\nFighting Stance!\n";
Sleep(3000);
cout << "C'ject!\n\n";
cout << "1 - Round Kick\n2 - Hook Kick\n3 - Front Kick\n4 - Side Kick\n";
cin >> kick;
if (kick == 1) {
roundKick();
}
cout << "Opponent used kick " << ekick;
if (blocked < 0.50) {
//
//
//I want to replace the 1 with the random Gen kick (ekick) to have the user know which kick it is
cout << kicks[1] << " to the body | Blocked\n";
} else
} else if (yn == "n") {
cout << "This is a sparring simulator, kid. Hit yes.\n\n";
goto syn;
}
return 0;
}
If you don't understand just tell me what you don't and I will try to make sense of it.
I'd suggest something like:
if(blocked < 0.50) {
ekick = okick(ranGen); // you had this in the code, but at a wrong place
cout << "Replied with " << kicks[ekick] << endl;
}
The problem is that you have the parts of the statements you need in the wrong place. You have defined and initialised these global variables at the beginning of your game, so they keep the same value throughout the game.
float landed = attack(ranGen);
float blocked = defense(ranGen);
float ekick; // we have now assigned ekick within the game. So here, just declare it
But I suppose you start learning. So we've solved the issue with ekick, but you've still a similar issue with landed and blocked. Up to you to solve it. Senpai ni rei !
P.S: immediately after you've done this, you should replace the horrible goto with a while loop. And later, one nice thing to improve would be to get rid of global variables

Alternative way for goto statement in C++

Here's the link for the flowchart:
http://i1146.photobucket.com/albums/o530/HTHVampire/C%20plus%20plus/Capture_zps5a6c3acf.jpg
Here's the code for the flowchart as shown, just ignore the ambiguous statement in the flowchart.
#include <iostream>
using namespace std;
int main()
{
//declare and initialize a variable
int a = 0;
//prompt user for a value
cout << "please enter a value" << endl;
cin >> a;
again1:
//enter a decision block
if(a > 10)
{
if(a < 10)
{
again2:
if(a < 100)
{
a = a - 3;
goto again2;
}
else goto again1;
}
else
{
a = a - 7;
goto again1;
}
}
else cout << "the output is " << a << endl;
return 0;
}
May I know that can I play this code with if-else statement together with while statement? instead of goto statement.
Thanks for your guides!
This structure should do the core logic according to the flowchart:
while (a > 10) {
if (a < 10) {
while (a < 100) {
a += 3;
}
} else {
a -= 7;
}
}
Note that the if test is absurd. However, I didn't draw the flowchart; I just reproduced it in code.
Nothing wrong with goto so long as you restrict use to state machines.
Many teachers erroneously ban use of it for lack of understanding.
For simple state machines like yours, and protocol decoding, it produces extremely readable code. I ruined years of embedded C routines because I was afraid to use goto.
I started using goto and my finger paintings turned into Van Gogh.