Open Side Menu Go to the Top
Register
First Programming Class: C++ First Programming Class: C++

05-11-2013 , 12:45 AM
Quote:
Originally Posted by sards
It is the same in C++. Get used to using F5, F10, and F11.
and F9, F12
First Programming Class: C++ Quote
05-11-2013 , 01:38 AM
It may run faster in release mode. (Though of course you can't do debugging then).
First Programming Class: C++ Quote
05-11-2013 , 01:49 AM
Quote:
Originally Posted by jmark
It may run faster in release mode. (Though of course you can't do debugging then).
Debugging in release mode is a good practice for production code. Change the compiler and linker settings to generate pdbs. With every build save the pdbs and source. Old people like me save the map files too.

This doesn't slow the code down at all. The binary is the same, but you have a pdb so the debugger can follow along. Sometimes there are small oddities due to optimization. A variable can get optimized out of existence. Lines can get skipped. But it's still a reasonable way to debug.

Then when you get crash dumps they are debuggable using the saved pdbs and source. If you don't save them then crash dumps are close to worthless.

Not that this matters for a homework assignment.
First Programming Class: C++ Quote
05-11-2013 , 02:36 AM
I think it would be faster in general if I just said

HTML Code:
if(composite) 
return false

else
return true
As it is I have an if statements that check for both composite and prime. Each time I try to just return true using the method above, my program messes up.
First Programming Class: C++ Quote
05-11-2013 , 06:23 AM
1. always use {} with if statements

2. Your isPrime has some style issues.

checker is a loop variable.

this is an initial condition:

Code:
int checker = 2;
this is an exit condition (and other stuff):

Code:
if(checker <= pow(n , .5) && n % checker == 0)
this is an update statement:

Code:
checker = checker ++;

this is how you make an infinite loop, or one that doesn't have the natural for flow:

Code:
for(;;) {
but as we just saw, your loop has all the classic for loop elements. So write it as such!

Code:
for(int ix = 2; ix <= pow(n, 0.5); ix++)
{
  if((n % ix) == 0)
  {
    return false;
  }
}
return true;
This line deserves special mention:
Code:
if(checker <= pow(n , .5) && n % checker == 0)
This is random nonsense. You are doing two unrelated things in the same line because ???
You have no parens ()! Which means you don't know what it actually does. The reader doesn't know what it actually does. Nobody knows the order of operations between { <=, &&, %, == }. I know what you wish the order was, but wishing doesn't make it so. Just always use parens whenever the whole world isn't absolutely sure about the order of operations. Otherwise you have bugs that your eye can't see.
First Programming Class: C++ Quote
05-11-2013 , 06:49 AM
Also I'm nervous about the sqrt check. I'm not sure about when a floating point is going to be exactly an integer. I'd be safe with:

Code:
ix <= (0.01 + pow(n, 0.5))
Google tells me you answer is right though.

Last edited by Chips Ahoy; 05-11-2013 at 06:54 AM.
First Programming Class: C++ Quote
05-11-2013 , 08:54 AM
Why use floating points or pow at all?

Code:
ix*ix < n
First Programming Class: C++ Quote
05-11-2013 , 11:22 AM
Thanks for the responses. I'm currently absorbing them.

I'm having a dense moment though: both of you wrote i as a coefficient of x and I'm not sure why. I see what the general statement cleverly does but I don't see why it wouldn't do the same thing without the x. Is it some sort of convention?
First Programming Class: C++ Quote
05-11-2013 , 02:07 PM
I was just copying from Chips, but I suspect it's a habit somehow passed down from Hungarian Notation: http://www.joelonsoftware.com/articles/Wrong.html

Quote:
Apps Hungarian had very useful, meaningful prefixes like “ix” to mean an index into an array, “c” to mean a count, “d” to mean the difference between two numbers (for example “dx” meant “width”), and so forth.
First Programming Class: C++ Quote
05-14-2013 , 07:22 AM
Quote:
Originally Posted by Chips Ahoy
Also I'm nervous about the sqrt check. I'm not sure about when a floating point is going to be exactly an integer. I'd be safe with:

Code:
ix <= (0.01 + pow(n, 0.5))
Google tells me you answer is right though.
Wtf is this???

Some of you should not be posting advice at all. The fact that you have generated a .c/.cpp file in your lifetime doesn't make you a programmer. You are going to confuse the guy.
First Programming Class: C++ Quote
05-14-2013 , 08:17 AM
Quote:
Originally Posted by tpir
Wtf is this???
This is a floating point comparison. The basic problem:

http://www.cygnus-software.com/paper...ringfloats.htm

Code:
float f = 0.1f;
float sum;
sum = 0;
 
for (int i = 0; i < 10; ++i)
    sum += f;
float product = f * 10;
printf("sum = %1.15f, mul = %1.15f, mul2 = %1.15f\n",
        sum, product, f * 10);
Quote:
Originally Posted by Comparing Floating Point Numbers
This code shows two ancient and mystical techniques for calculating ‘one’. I call these techniques “iterative-adding” and “multiplying”. And, just to show how messy this stuff is I do the multiplication twice. That’s three separate calculations of the same thing. Naturally we get three different results, and only one of them is the unity we were seeking:

sum=1.000000119209290, mul=1.000000000000000, mul2=1.000000014901161

Disclaimer: the results you get will depend on your compiler and your compiler settings, which actually helps make the point.
As a general rule, floating point results are inexact. Prudent, experienced C programmers do not compare the result of a floating point calculation for equality. Instead they check if the result is "close enough" -- within some epsilon.

Consider a sqrt implementation that returns 2.9999999999996443 for sqrt(9). In that case -- without the + 0.01 -- IsPrime(9) would return true!

Now I recall from having worked with lua that integers have exact representations as doubles:

Quote:
The fact is that, when you use a double to represent an integer, there is no rounding error at all (unless the number is greater than 100,000,000,000,000).
http://www.lua.org/pil/2.3.html

Which is helpful. It means there are no cases that are guaranteed to fail below 10^14. It also means there are cases that are guaranteed to fail above 10^14. Single precision will fail lower.

There is the more serious matter of the implementation of pow(). That is a black box and could have accumulated error in it afaik.

Quote:
Some of you should not be posting advice at all. The fact that you have generated a .c/.cpp file in your lifetime doesn't make you a programmer. You are going to confuse the guy.
oic.

I think "always use an epsilon instead of equality checks with floating point" is a pretty good rule. The result is code that always works. The alternative is either a hard to find corner case or spending precious developer time deciding an equality check will work.
First Programming Class: C++ Quote
05-14-2013 , 12:20 PM
Not a C / C++ programmer, but I would just avoid using floats when they aren't needed.
First Programming Class: C++ Quote
05-14-2013 , 12:44 PM
EDIT: Nevermind, I messed something up. Chips is actually completely right here.

I'll also note that I think mine is more elegant but also risks hitting overflow sooner, since it breaks around sqrt(MAX_INT). I've become accustomed to Python's automatic bigint promotion...

Last edited by Xhad; 05-14-2013 at 12:50 PM.
First Programming Class: C++ Quote
05-17-2013 , 11:33 AM
The idea of a "reference parameter" as in the following code:

HTML Code:
void averageAndGrade(int testScore, int progScore, double& average, char& grade) {
average = (testScore + progScore) /2.0;

etc
etc

}
Does writing "double& average" actually tell the computer to do anything, or is it simply drawing the users attention to the fact that this variable is different from the others in the sense that it will hold the value of the parameters testScore and progScore?

I don't understand the necessity of adding&.
First Programming Class: C++ Quote
05-17-2013 , 02:04 PM
I'm running into a problem while making a palindrome checker. I've gotten it to work fine except for in the case where the string ends in a punctuation mark. I believe that the problem is caused as a result of either one or both the following two procedures:

1) punctuation is removed from a string by replacing punctuation with " "
2) char by char comparison is done. If punctuation is replaced with a space at the end of a string then the first character in our string != last character in the string because last character is a space.

I've put comments next to the two spots that I think could be the problem

HTML Code:
#include <iostream>
#include <string>
#include <cctype>

using namespace std;
string cleanUp(string& phrase);
bool isPalin(string cleanedPhrase);
int main() {
	string userPhrase;
	
	cout << "Please enter your word/phrase: " ;
	getline (std::cin, userPhrase); 
	
	isPalin(cleanUp(userPhrase));
	if (isPalin(cleanUp(userPhrase))) {
		cout << "is palin";
	}
	else
		cout << "no";

	getchar();
	getchar();
	return 0;
}
string cleanUp(string& phrase) {
	for (int i = 0; i < phrase.length(); i++)
    {
		if (isupper(phrase[i]))
        {       
			phrase[i]=tolower(phrase[i]) ;
        }       
        if (ispunct(phrase[i])) 
		{
			phrase[i]=' ';	// i think this is where the problem is
		}
	}
	return phrase;
}

bool isPalin(string cleanedPhrase) {
	for( int i = 0; i < cleanedPhrase.length() / 2 ; i++) {
		if( cleanedPhrase[i] != cleanedPhrase[cleanedPhrase.length()-1-i]) // could be this procedure as well
			return false;
	return true;
	}
}
First Programming Class: C++ Quote
05-17-2013 , 03:07 PM
I also just ran into a problem where I checked
"madam my name is adam"
and the program reads it as a palindrome.

Is there a reason that it would stop comparing chars once it got to the white space that comes prior to adam?

Last edited by Acemanhattan; 05-17-2013 at 03:22 PM.
First Programming Class: C++ Quote
05-17-2013 , 03:57 PM
Quote:
Originally Posted by Acemanhattan
Does writing "double& average" actually tell the computer to do anything, or is it simply drawing the users attention to the fact that this variable is different from the others in the sense that it will hold the value of the parameters testScore and progScore?
Yes, adding the & actually does something. It allows you to modify the variable that is passed in as a reference. Like so:
Code:
void squareByReference(int& x)
{
    x = x * x;
}

void squareByValue(int x) // note the lack of &
{
    x = x * x;
}


int a = 5;
squareByReference(a);
cout << a; // prints "25"
squareByReference(5); // ERROR: must pass variables by reference, not literals.
a = 3;
squareByValue(a);
cout << a; // prints "3". The value of a is not changed.
squareByValue(3); // No error, but has no effect.
Quote:
Originally Posted by Acemanhattan
I'm running into a problem while making a palindrome checker.
Check the position of "return true" in isPalin(). This bug was probably caused by your haphazard use of indentation and curly brace placement. You should really pick one of the standard styles for indentation and bracing and stick to it. It will make your code easier to read and help to avoid bugs like this.
First Programming Class: C++ Quote
05-17-2013 , 05:05 PM
Quote:
Originally Posted by Acemanhattan
The idea of a "reference parameter" as in the following code:

HTML Code:
void averageAndGrade(int testScore, int progScore, double& average, char& grade) {
average = (testScore + progScore) /2.0;

etc
etc

}
Does writing "double& average" actually tell the computer to do anything, or is it simply drawing the users attention to the fact that this variable is different from the others in the sense that it will hold the value of the parameters testScore and progScore?

I don't understand the necessity of adding&.
It tells the compiler to do something, not the computer.
First Programming Class: C++ Quote
05-17-2013 , 05:43 PM
Thanks. Resolved the issue with a lot of googling, but it did end up being an issue of where I was returning true.
First Programming Class: C++ Quote
05-23-2013 , 12:40 PM
I have the below written into my main function but what I'd like to have is a function that does the same thing (counts the occurrences of letters from a text document) and then is able to pass the array into another function so that it can be sorted to find out which index corresponds to the highest occurring letter. Can I actually return an array from a function?

HTML Code:
while (!fromFile.eof()){
	fromFile >> ch;
	ch = toupper(ch);
	index = ch -'A';
	if(index < 26 && index >= 0) {
		letterCount[index]++;
	}
}
First Programming Class: C++ Quote
05-23-2013 , 01:55 PM
It's probably easier to just work with the pointer to the array, as long as you've allocated the array properly so that it doesn't disappear when you leave the function.
First Programming Class: C++ Quote
05-23-2013 , 02:23 PM
I decided I don't want to make this more complicated than it has to be; I'm only 8 weeks into this class right now so if everything I do is just a convoluted hack until I get more intuition, so be it.

Now I need to read letters and shift them by an amount called "shift" that is established by my previously written code. E.g. if my shift needs to be 3 to the left then 'c' needs to turn into 'a', 'a' needs to turn into 'x' etc etc.

How do I make this work for my end cases? I know that I can just use something like
HTML Code:
ch = static_cast<char>(ch - shift)
except that if I'm at, say, 'a', it will convert 'a' into some character like '^', which is bad for me.

Thoughts?
First Programming Class: C++ Quote
05-23-2013 , 04:27 PM
You can check if it's less than 'a' then add 26
First Programming Class: C++ Quote
05-23-2013 , 09:32 PM
I'm really struggling here.
I'm trying read letters from a text file into a function and then increment corresponding indexes in an array inside of the function.

Eventually I will want to write a function that finds out which index in the array has the highest count.

So here is what I have. I don't know if my function should be of the void type, if it should take different input than char (like instead intake an entire array). Any direction would be great.


HTML Code:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;

void counter(char ch);

int main() {
	
	// Declaring variables for use throughout program
	ifstream fromFile;
	string fileName;
	char ch;

	// Prompting user to enter file name and opening file
	cout << "Please enter the file name you wish to open : "; 
	cin >> fileName;
	cout << endl << endl;
	fromFile.open(fileName.c_str());
	
	// If a file is not found in the location suggested by the user 
	// an appropriate error message outputs and the program quits.
	if (!fromFile.is_open()) {
		cout << "An error has occured.  File name not found." << endl;
		getchar();
		getchar();
		return 0;
	}
	
	while (!fromFile.eof()){
		fromFile >> ch;
		counter(ch);
	}

	getchar();
	getchar();
	return 0;
}


void counter(char ch) {
	int index;
	int letters[26] = {0};

		ch = toupper(ch);
		index = ch -'A';
		if(index < 26 && index >= 0) {
			letters[index]++;
			
		}
	}
First Programming Class: C++ Quote
05-23-2013 , 10:32 PM
You need to declare the counting array letters[] outside the counter function! Otherwise it's not going to keep the count between function calls.

Otherwise the approach seems fine, if you don't care about uppercase/lowercase distinction.
First Programming Class: C++ Quote

      
m