Newbie C++ question about functions and error checking - c++

Am working on a small problem and have spent quite a few hours trying to figure out what I did wrong. Using Dev++ compiler which at times has some cryptic error messages.
I tried to make the Volume calculation a function and got it to work but I have 2 small nits. Will work on error checking after I resolve this.
With the function added, for some reason with dev++ now, the program does not pause (press any key to continue).
Volume is coming up with blank instead of a number.
Thanks
PC
// The purpose of this program is to determine the Volume of a
// square-based pyramid after the user inputs the Area and
// the Height.
#include <iostream>
#include <iomanip>
using namespace std;
double calcvolume(double a, double h)
{
double volume;
volume = ( a * h ) / 3;
return (volume);
}
int main()
{
double area, height, volume; // declare variables
cout << "Please enter the Area of the Square-based pyramid:"; // requests users input
cin >> area; // assigns user input to area
cout << "Please enter the Height of the Square-based pyramid:"; // requests user input
cin >> height;
// assigns user input to height
cout << "Area= " << area << "\n"; // Prints user input for area
cout << "Height= " << height << "\n";
calcvolume(area,height);
cout << "Volume= " << fixed << showpoint << setprecision(2) << volume << "\n"; // Prints resolution to the formula stored in volume
system("pause"); // forces DOS window to pause to allow user to utilize program
return 0;
}

Your updated code looks correct, but you aren't storing the calcvolume return value. The volume variable you declare in calcvolume is different than the one you declare in main. Each of these variables can only be referenced from within the function it is declared in.
In order to save the volume,
calcvolume(area,height);
should be
volume = calcvolume(area,height);
This will store the value being returned from calcvolume in the volume variable in your main function.

You have to assign the result of calcvolume(area,height) to main's volume as follows:
volume = calcvolume(area,height);
Now you can safely use main's volume variable.
I'm guessing that your program was not even reaching the system("pause") line, and was crashing the line above. It could be because volume was never set to anything and was holding garbage data. This garbage data made cout << ... fail.
Before you fix the calcvolume(area,height) line, try fixing your variable declarations so that your variables are initialized to zero:
double area=0.0, height=0.0, volume=0.0; // declare variables
Now run it again and see if it outputs Volume=0.00 and pauses.
It's always good to initialize your variables to zero or something meaningful. Otherwise, they will be initialized to random data (whatever was already in those memory bytes) and will make troubleshooting more difficult.

Related

warning: 'totalTemp' may be used uninitialized in this function and cout not printing to console

Trying to write a program displaying the average temperature in 24 hours, by the user typing in the temperature each hour. However, I'm just getting this error in code blocks:
warning: 'totalTemp' may be used uninitialized in this function [-Wmaybe-uninitialized]|.
and the console is just black when ran and not displaying anything.
#include <iostream>
using namespace std;
int main(void)
{
int i = 0;
while(i <= 24);
int newTemp;
int totalTemp;
{
cout << "Input temperature for the hour " << i << ":";
cin >> newTemp;
totalTemp = totalTemp + newTemp;
i++;
cout << "The average temperature for the day is " << totalTemp/24 << " degrees";
}
return (0);
}
How do I initialize it? and what is making my code not appear in the console when I'm trying to use cout?
How do I initialize it?
int totalTemp = 0;
and what is making my code not appear in the console when I'm trying to use cout?
while(i <= 24);
This is an infinite loop with an empty body. Infinite loops without observable side effects are undefined behavior. The compiler is allowed to produce the same output for your code as it would for int main() {}. You probably want while( i<=24) { .... Or rather use a for loop when the number of iterations is fixed.
Moreover, totalTemp/24 is using integer arithmetics. Maybe thats what you want, but more likely you want totalTemp/24.0. And also very likely you want to print the average outside of the loop instead of printing it in every iteration.

uninitialized local variable error even thought I initialized it (C++)

I'm pretty new to programming and not sure what I did wrong but I'm getting the error on line 20, it says that I haven't initialized intownMiles and highwayMiles.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double intownMPG = 23.5;
double highwayMPG = 28.9;
double intownMiles;
double highwayMiles;
double gallons = intownMiles / intownMPG + highwayMiles / highwayMPG;
cout << "Please enter the number of in-town driving miles: " << endl;
cin >> intownMiles;
cout << "Please enter the number of highway driving miles: " << endl;
cin >> highwayMiles;
cout << "The total number of gallons required is: " << gallons << "gal" << endl;
}
Your code:
double intownMiles;
double highwayMiles;
double gallons = intownMiles / intownMPG + highwayMiles / highwayMPG;
You clearly have not initialized those variables before using them. All you did was define them - so they exist, but have indeterminate values until you assign to them (which you never do).
Initialize the variables to sane initial values when you define them and the compiler warning will go away (and your code will no longer have Undefined Behaviour).
Writing C++ is different from writing regular math equations.
Firstly, the code is executed sequentially.
When execution reaches this line:
double gallons = intownMiles / intownMPG + highwayMiles / highwayMPG;
The value of gallons is computed immediately, using the current values of variables used in the expression.
You haven't assigned any values to some of the variables prior to using them, so you can't expect to get a meaningful result.
When you change those variables later, the value of gallons is not affected.
So you have to ask the user for values of those variables first, and then compute the formula.

(C++)1 dimensional battleship game help? advice for improvement

Unfortunately I do not have the Instructor to aid me with this assignment over the weekend and I am stuck. I'm just learning C++ and I've taken a Logic and Design class for Programming but like I said I'm very new to C++. I'm having a hard time catching up to the rest of the students.
I'd like if someone could list improvements and maybe clarify if I've done anything wrong in comparison to the assignment statement. I do really appreciate the help!
My code is repetitive and I'm sure I could go another way into displaying the array values without all that code. An error also pops up after use of the application that says:
"Run-Time Check Failure #2 - Stack around the variable 'enemy' was corrupted.
If there is a handler for this exception, the program may be safely continued."
The assignment is:
"Create a Battleship struct containing 5 one-dimensional integer coordinates representing its location within a region (of any size). Instantiate 2 copies of the struct and have the user enter a single coordinate for each Battleship. Design your code to take this single coordinate and use it to populate the remaining 4 coordinates for each ship. Do this for both ship structs. Then, have your code calculate the numeric distance between the 2 ships based on their respective coordinates. Finally, display the resulting distance to the user with an English language sentence."
My code as for right now is :
#include <iostream>
#include <string>
using namespace std;
struct Ship
{
int x[5];
int y[5];
};
int main()
{
Ship good;
Ship enemy;
good.x[0] = 0;
enemy.y[0] = 0;
cout << "Enter a coordinate (out of 100) for good ship: "<< endl;
cin >> good.x[0];
good.x[1] = good.x[0] + 1;
good.x[2] = good.x[1] + 1;
good.x[3] = good.x[2] + 1;
good.x[4] = good.x[3] + 1;
cout << "Good ship coordinates:" << endl;
cout << good.x[0]<< "*" << endl;
cout << good.x[1]<< endl;
cout << good.x[2]<< endl;
cout << good.x[3]<< endl;
cout << good.x[4]<< endl;
cout << "Enter a coordinate (out of 100) for enemy ship: "<< endl;
cin >> enemy.y[0];
enemy.y[1] = enemy.y[0] + 1;
enemy.y[2] = enemy.y[1] + 1;
enemy.y[3] = enemy.y[2] + 1;
enemy.y[4] = enemy.y[3] + 1;
cout << "enemy ship coordinates:" << endl;
cout << enemy.y[0]<< "*" << endl;
cout << enemy.y[1]<< endl;
cout << enemy.y[2]<< endl;
cout << enemy.y[3]<< endl;
cout << enemy.y[4]<< endl;
int distance=0;
distance = good.x[1] - enemy.y[1];
cout << "The distance between good ship and enemy ship is: " << distance << endl;
system("pause");
return 0;
}
The error probably comes from having only 4 coordinates in each struct, not 5. When you declare an array with int x[4];, it will only have 4 elements, namely x[0] to x[3].
There are a number of other problems:
You do not need two structs for two ships. Use just one. That's the whole point of structs/classes: to represents classes of objects. Use only one struct (named e.g. Ship) and declare both your ships good and enemy to have that type.
Don't be afraid of both the enemy ship and the good ship having x coordinates. The compiler and the computer won't get confused at that, and neither should you.
Learn to use loops. Even if you get confused at first, remember that loops are one of the most (if not the most) important tools at a programmers disposal. Think what would happen if you had 100 ships, each with 100 coordinates...
Remember, again, that the first element of an array is at index 0, not index 1. (And the last element is at index N-1.)
Calculating the distance is a little more complex than you've written. Can the distance between two objects ever be negative? What happens if the enemy ship's coordinate is greater than the friendly ship? What's the actual formula for one-dimensional distances?
Remove unused code. What's the use of that region variable? Have you used it anywhere?
UPDATE: (For anyone reading in the future, remember that OP has updated and modified their question and code, to the point that some of my point would not apply or would apply differently.)
Do you REALLY need both xs and ys in Ship?
Not sure if the use of system("PAUSE") is something your instructor taught, but that's definitely something you could improve on, too. Explained here
So starting with
Create a Battleship struct containing 5 one-dimensional integer coordinates representing its location within a region (of any size). Instantiate 2 copies of the struct and have the user enter a single coordinate for each Battleship
You need a single struct:
struct Ship
{
int x[5];
};
Now make 2 copies
int main()
{
Ship good;
Ship bad;
...
Then the rest looks good, it compiles and runs without any issues on my computer. You can add a function to populate the ship to reduce the number of code
Ship createShip(int startPos) {
Ship newShip;
newShip[0] = startPos;
// ... <- rest of your code that you have to populate
return newShip;
}
int main()
{
int pos;
cout << "Enter a coordinate (out of 100) for good ship: "<< endl;
cin >> pos;
Ship good = createShip(pos);
//...
//... <- Get pos of bad ship
Ship bad = createShip(pos);
}
Then you can also create a simular function that prints the location of the ship

Visual C++ - Runtime Check Failure #3 - Variable is not initiliazed

I use Visual C++ 2010 Express Edition to compile and run the .exe files I write in the C++ programming language. I am trying to create a loop-based logic using C++ to ask the user how many entries he chooses to enter, and ask questions limited to that no. of entries. For example I want to output, "How many characters do you wish to enter?: " Say the user gives the answer as '3' which is stored in the int variable 'entries'. I then want to keep asking the question 3 times before it stops and continues with the next line of code. I hope you understand, here is a block of code to demonstrate what I am doing:
#include <iostream>
#include <string>
using namespace std;
int main()
{
cout << "How many values do you need to enter?: ";
int entries;
cin >> entries;
int offset, number;
string valueName[50];
float valueValue[50];
for (offset = 0; offset < entries; offset++)
{
cout << "Enter " << number << " Value Name: ";
cin >> valueName[offset];
cout << "Enter " << valueName[offset] << "\'s value: ";
cin >> valueValue[offset];
for (number = 1; number <= entries; number++)
{
}
}
char response;
cin >> response;
return 0;
}
Strangely when I run this simple program, it fails when I enter the value's name to be inserted into the 0th element of the valueName[] array. It just pauses the execution of the program and a dialog box pops up saying "Runtime Check Failure #3 - Variable 'number' is being used without being initialized!" Another problem regarding this program is that, for quite some time, when I ran this program this "Runtime Check Failure #3" box never appeared, and when it didn't, the number value went wrong, and first started with 1, and then for the next loop jumped to 6, and then repeated 6 again for the next loop! Please help me! I've checked online scouring this problem everywhere, but it just doesn't apply to my type of problem! Is it because the variables are out of scope? But they're declared outside the for loops right? So please help me!
The runtime is telling you the truth, the following line comes after you have declared number as an int but have not given it a value.
cout << "Enter " << number << " Value Name: ";
In your code you declare the following, in C++ this means give me 2 ints but the values are not defined yet, e.g.
int offset, number;
Change it to something like this ..
int offset = 0;
int number = 0;
You are printing the variable number without assigning to it first, i.e. it's uninitialized. When it prints some random number it's because that what happens to be in the memory at the time you run the program. Assign a value to it before you use it.
The problem is exactly the error message you're getting. You're using the variable number without initializing it.
You use the variable right here, at the top of your loop, when it hasn't been initialized to anything yet:
cout << "Enter " << number << " Value Name: ";
What is your intention with the number variable? It doesn't really seem to be serving any purpose. If you want to print which entry you're currently on, you could use the offset variable instead, like this:
cout << "Enter " << offset << " Value Name: ";
But that still seems a little unclear to me.
But the reason that you're having a problem is because the value is uninitialized, so you're experiencing undefined behavior. This is also the reason that Visual Studio doesn't always catch it; it will probably always catch in Debug mode, but in Release mode it will almost never catch it. You need to initialize all your variables before you use them.
In my case it was because an extern variable was declared twice.

Variable not accessible within an if statement

I have a variable which holds a score for a game.
My variable is accessible and correct outside of an if statement but not inside as shown below
score is declared at the top of the main.cpp and calculated in the display function which also contains the code below
cout << score << endl; //works
if(!justFinished){
cout << score << endl; // doesn't work prints a large negative number
endTime = time(NULL);
ifstream highscoreFile;
highscoreFile.open("highscores.txt");
if(highscoreFile.good()){
highscoreFile.close();
}else{
std::ofstream outfile ("highscores.txt");
cout << score << endl;
outfile << score << std::endl;
outfile.close();
}
justFinished = true;
}
cout << score << endl;//works
EDIT:
have realised my problem, when I was printing out it looped through many times so I did not see that all of them for the first loop didn't work, hence I thought the others were working when in fact they were not for the first iteration.
This is not a problem relating to the scope of the variable.
It could be several things:
Memory corruption somewhere
Multi threading relating problem
Something else...
Are you sure you are looking at the same iteration where the score value works before and after but not inside? Maybe put some more detailed logging instead of simply outputting the score itself.
Try printing cout << score << "#" << &score << endl; each place you currently print score. This will let you check if you're actually looking at the same variable.
If the addresses are different, you're accidentally shadowing your score variable somewhere - gcc has -Wshadow to catch that.
If the addresses are the same then the variable is getting corrupted somehow. Most debuggers have a memory breakpoint feature, so you can set the debugger to break when the memory in score changes and find the culprit.
With the amount of code you have attached there is nothing to indicate there is a problem in the code. As Brian says it is something else
Can you try this in your debugger and see what happens ? The idea is to simplify the problem as much as possible and try to get the minimal amount of code that replicates the problem.
What does this do ?
cout << score << endl; //works
if(!justFinished)
{
cout << score << endl; // doesn't work prints a large negative number
}
cout << score << endl; //works