• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

C++ Help?

Status
Not open for further replies.

Toby

Member
double calculateCharges(double hoursParked)
double charges=2;
if(hoursParked>3)
{
charges=charges+(hoursParked*.5)//might want .5 as a variable
}
if(hoursParked>19)
//16*.5=8, 8+2 is 10, if over 19, want to set charge to maximum, not more
{
charges=10;
}
return charges;

that help?
 
the else if part will never be exicuted because > 19 implies > 3 as well. your statment should have the form

if(time <= 3 hours){
return 2
}else if(time < 11 hours){
return ceil((time-3)*0.5)+2
}else{
return 10
}
 

deadbeef

Member
Kccitystar said:
OK, so I'm pretty stuck here.

There are a few things I am stuck with as I don't know how to code that well, and my professor has given me two problems to work on:

1) A parking garage charges a $2.00 minimum fee to park for up to three hours. The garage charges an additional .50 per hour for each hour or part thereof in excess of three hours. The maximum charge for any given 24-hour period is $10.00. Assume that no car parks for longer than 24 hours at a time. Write a program that calculates and prints the parking charges for each of three customers who parked their cars in this garage yesterday. You should enter the hours parked for each customer. Your program should print the results in a neat tabular format and should calculate and print the total of yesterday's receipts. The program should use the function calculateCharges to determine the charge for each customer.

2)Write program segments that accomplish each of the following:
a) Calculate the integer part of the quotient when integer A is divided by integer B.
b) Calculate the integer remainder when integer A is divided by integer B.
c) Use the program pieces developed in (a) and (b) to write a function that inputs an integer between 1 and 32767 and prints it as a series of digits, each pair of which is seperated by two spaces.


So many things to do and I don't know where to start. Fuck my life.

Can anybody help?



Sure, man

Code:
  #define MIN(A,B) ((A < B) ? A : B)

  double calculateCost(double h)
  {
    double cost = (2 * (h > 0.0)) + ((h > 3.0) ? (0.5 * ceil(h - 3.0)) : 0);
    return MIN(cost, 10.0);
  }

Pardon my printf, I'm a C programmer at heart. :)

Oh here's another way:

Code:
  #define MIN(A,B) ((A < B) ? A : B)

  double calculateCost(double h)
  {
    double costs[] = {0.0,2.0,2.0,2.0,2.5,3.0,3.5,4.0,4.5,5.0,5.5,6.0,
                  6.5,7.0,7.5,8.0,8.5,9.0,9.5,10.0,10.0,10.0,10.0,10.0,10.0,10.0};

    return costs[(int)ceil(h)];
  }

Oh, here's another one using recursion!

Code:
#define MIN(A,B) ((A < B) ? A : B)

// precondition: 0 <= hours <= 24
double calculateCost(double hours)
{
  if(hours <= 3)
    return 2.0;
  else
  {
    double cost = 0.5 + calculateCost(hours - 1.0);
    return MIN(cost, 10.0);
  }
}
 

Kccitystar

Member
For the first problem, this is what I have:

Code:
#include <iostream>
using namespace std;
void calculateCharges(int);
void main()
{
	int hours, people;
	cout<<"enter how many customers "<<endl;
	cin>>people>>endl;
	cout<<"enter how many hours "endl;
	cin>>hours<<endl;
	
		calculatecharges(hours, people)
}
    void calculatecharges(int num1, int num2)
	{
		int bill;
		bill= num1*num2
	}
 

Zoe

Member
Sounds like you're misunderstanding the question. Here's what you need:

- A way to store multiple hours
- A function to calculate the cost based upon those hours (it's not hours * people)
- A way to iterate over your stored hours to generate the cost
- A printout of each calculated total
 

dc`

Neo Member
deadbeef said:
Sure, man

[...]

Oh, here's another one using recursion!

Code:
// precondition: 0 <= hours <= 24
double calculateCost(double hours)
{
  if(hours <= 3)
    return 2.0;
  else
  {
    return 0.5 + calculateCost(hours - 1.0);
  }
}
You aren't taking into account the maximum cost of $10.00. Also I'm not sure double is necessary if you're calculating dollar values and limiting to two decimal places ;)

Code:
#include <stdio.h>
#include <math.h>

float calculateCharges(float hours)
{
        float total=2.0f;
        float integral = floor(hours);

        if(hours<=3) {
                /* keep the total at $2.00 */
        } else if(hours>=19) {
                total=10.0f;
        } else {
                total+=((integral-3)/2);         /*$0.50 per hour after 3*/
                if(hours-integral>0) total+=0.5; /*$0.50 per part of hour*/
        }

        printf("\t$%.2f\t%.2f\n",total,hours);

        return total;
}

int main(int argc, void *argv[])
{
        float cara,carb,carc,total=0.0f;
        int x;
        fprintf(stdout,"Enter the hours\n");
        scanf("%f",&cara);
        scanf("%f",&carb);
        scanf("%f",&carc);
        

        fprintf(stdout,"Car\tPrice\tHours\n");
        fprintf(stdout,"Car 1");
        total += calculateCharges(cara);
        fprintf(stdout,"Car 2");
        total += calculateCharges(carb);
        fprintf(stdout,"Car 3");
        total += calculateCharges(carc);
        fprintf(stdout,"Total:  $%.2f\t%.2f\n",total,cara+carb+carc);

        return 0;
}
 

deadbeef

Member
dc` said:
You aren't taking into account the maximum cost of $10.00

Hmm, good point. This exercise is left to the reader ;)

Okay, I think I fixed it. Thanks!

dc` said:
Also I'm not sure double is necessary if you're calculating dollar values and limiting to two decimal places ;)



LOL, oops.
 

Kccitystar

Member
I'm going to try and clean this up, this is what some friends and I compiled so far.

Code:
#include <stdio.h>
#include<iostream>
#include <string>
#include <iostream>
#include <iomanip>

using namespace std;

const int CARS = 10;
static int hours[CARS] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

void enterHoursParked()
{
for(int i=0;i<CARS;i++)
{
       cout << "Please input hours parked for car number "<< i;
       cin >> hours[i];
}

}

float calculateCharges(int ilen)
{
float finalCharge;

if (ilen <= 3)
finalCharge = 2;
if (ilen >= 19)
finalCharge = 10;
if (ilen > 3)
finalCharge = 2 + (float)(ilen - 3) * .50;


return finalCharge;
}
void printCharges(int carno, int hours, float finalCharge)
{
if(carno == 0)    
cout << "Car     Hours    Charge\n";
else
cout << (carno)<<"         "<< hours<<"      "<< finalCharge<<"\n";


}


int main()
{

cout << "Parking Garage Calculator" << endl;
enterHoursParked();

for (int i = 0; i <= CARS; i++)
{
float finalCharge = calculateCharges(hours[i]);
printCharges(i,hours[i],finalCharge );

}

 
int l;
cin>>l;  

return 0;
}
 

dabig2

Member
Kccitystar said:


A couple things:
-Be careful about your for loop in main where it calculates the charges. You have an array of 10 CARS, but the index of that array goes from 0 to 9. As you have it now with i<=10, it's going to execute when i = 10 and that's going to give an outOfBounds error for that array. Change it to i< CARS

-Change your if statements in the calculate method to this:
Code:
if (ilen <= 3)
      finalCharge = 2;
else if (ilen >= 19)
       finalCharge = 10;
else (ilen > 3)
finalCharge = 2 + (float)(ilen - 3) * .50;
This is because as you have it now, even if you have 24 hours, it'll actually execute the bottom 2 statements even though you only want it to execute that 2nd if.

edit:Oh, and forgot to mention your printCharges function. Change it to this:
Code:
if(carno == 0)    
   cout << "Car     Hours    Charge\n";

//you want to do this part regardless. It's not connected at all to above if
cout << (carno)<<"         "<< hours<<"      "<< finalCharge<<"\n";

The way you had it, it wouldn't print out the first car's information. It sees that if-else and executes your if statement which prints the header, but it actually never prints the information for that first car as the else is skipped.
 

Zeppu

Member
I don't understand why people are doing the hrs > 19 thing. That's additional logic which you don't need to calculate yourself. The condition is > $10, just stick to that and don't create extra shit for yourself since, in reality while this is just a silly little project if you do that kind of shit in real life you get yourself or someone else confused the fuck out as to where the 19 hrs came from.

Code:
float MAX_CHARGE = 10.0;
float EXCESS_CHARGE = 0.5;

float calculateCharges(float hours) // assume 15 mins = 0.25 etc...
{
float charge = 2.0;     
float extraHours = hours - 3;
if (extraHours > 0) 
{
    extraHours = ceil(extraHours); // round up hours
    charge += extraHours * EXCESS_CHARGE;       
}
return charge>MAX_CHARGE?MAX_CHARGE:charge;     
}

2)Write program segments that accomplish each of the following:
a) Calculate the integer part of the quotient when integer A is divided by integer B.
b) Calculate the integer remainder when integer A is divided by integer B.
c) Use the program pieces developed in (a) and (b) to write a function that inputs an integer between 1 and 32767 and prints it as a series of digits, each pair of which is seperated by two spaces.

Lulz, I dunno about c but a and b are dead easy.

div_t answer = div(A,B);
answer.quot <-- quotient
answer.rem <-- remainder
 

CrankyJay

Banned
Yeah. Don't have a condition for >= 19 ... this isn't what your professor is looking for, and is considered hackery.

Code:
const float MAX_CHARGE = 10.00;
const float RATE = .5;

float calculateCharge(int hours)
{
    float charge = 2.0;

    float calc = hours * RATE;

    if (hours > 3 && calc <= MAX_CHARGE))
    {
         charge = calc;
    }
    
    return charge;
}

edit: I just realized the professor didn't specify how hours is represented. I guess it could be fractional or whole hours, but from my experience parking garages don't pro-rate fees based on 15 minute increments so that's why I went with whole hours.
 

dc`

Neo Member
CrankyJay said:
Yeah. Don't have a condition for >= 19 ... this isn't what your professor is looking for, and is considered hackery.

Code:
const float MAX_CHARGE = 10.00;
const float RATE = .5;

float calculateCharge(int hours)
{
    float charge = 2.0;

    float calc = hours * RATE;

    if (hours > 3 && calc <= MAX_CHARGE))
    {
         charge = calc;
    }
    
    return charge;
}

edit: I just realized the professor didn't specify how hours is represented. I guess it could be fractional or whole hours, but from my experience parking garages don't pro-rate fees based on 15 minute increments so that's why I went with whole hours.
This does not return the correct results, and the description specified that there can be part hours: ".50 per hour for each hour or part thereof"
 

Relix

he's Virgin Tight™
I need a good C++ IDE. Any recommendations? Code:Blocks won't work well. It doesn't do includes, and yes I have Mingw installed.

For example... include <iostream> won't work at all, nor any other includes.

So... I am looking for an alternative. Tips?
 

Zoe

Member
^ Visual Studio. All Express versions are free, and most students qualify for free versions of the full product.
 

Chichikov

Member
Zoe said:
^ Visual Studio. All Express versions are free, and most students qualify for free versions of the full product.
Indeed, and Express should be fine for most things anyway; it's most certainly more than enough for learning.

Though Relix's include problem is most likely easily solvable.
 

Relix

he's Virgin Tight™
Yeah I got Visual C++ .NET already installed. Tried to get myself out of that IDE but its working fine so... =P!.

I have experience with .NET so it's probably the easiest for me to go into.

Will stick to that then (and try Xcode).

Zoe said:
That is true. Sounds like something's wrong with the settings.

Can't find it :lol :lol
 

Chichikov

Member
Relix said:
Yeah I got Visual C++ .NET already installed. Tried to get myself out of that IDE but its working fine so... =P!.

I have experience with .NET so it's probably the easiest for me to go into.
There's really no such thing as C++ .NET, there's MCPP or C++/CLI (same thing, different names) but I don't think there's a specific IDE for it.
The Visual Studio C++ should support vanilla C++ just fine.

Relix said:
Can't find it :lol :lol
Can you find the h files themselves?
 
ianp622 said:
Once you learn a programming language, you shouldn't really need to spend any money to learn another one. You should be able to pick it up with books or online resources.

What kind of job are you looking for?
Unless it's something that uses a different programming paradigm, like F# or Haskell, in which case it feels like you just started programming. (did some stuff in F# over the summer, it's fun but not that easy to pick up, as I'm usually doing stuff in Java)
 

CrankyJay

Banned
dc` said:
This does not return the correct results, and the description specified that there can be part hours: ".50 per hour for each hour or part thereof"

Oh. Whatever. Did this first thing this morning.

The program requirements are shit. He doesn't define what part thereof means. Does he want the price pro-rated per minute? Per 15 minute increment? 30 minute? What the fuck is a part?
 

Toby

Member
CrayzeeCarl said:
This looks like a good C# book.
Thanks for suggesting that book. Went and picked it up today, ended up pretty cheap. Thanks to all the other suggestions as well.
Ended up in the Java class, BTW. That and software engineering should keep me busy.
 

CrankyJay

Banned
Toby said:
Thanks for suggesting that book. Went and picked it up today, ended up pretty cheap. Thanks to all the other suggestions as well.
Ended up in the Java class, BTW. That and software engineering should keep me busy.

Well, the cool part about Java is you'll get a good background in OOP and should be able to pick up C# pretty easily.
 

poweld

Member
Relix said:
I found the h files, but the system won't work with them.
Please stop wasting everybody's time and get a IDE that is known, i.e. Visual Studio Express.

Sorry if this seems harsh, I just don't see the point in your using something nobody's ever heard of and then asking for help.
 

Minamu

Member
I'm trying to make a dice throwing game and I can't figure out how to make my "account" I store my virtual money in persistent between matches so to speak. For the time being, I'm simply using return int main() when the game asks me if I want a rematch. And of course, resetting int main means that "account" goes back to 0 since the very first thing the program asks for is place a maximum of 5000 in a betting account, which I withdraw from with each bet I make). It's for a programming for dummies course so I don't have a ton of experience with this stuff :S

It could probably be fixed with functions but I don't really have any experience with that and while we are allowed to use them, it should be totally possible to crack this nut with just basic programming skills and if/while/for code because that's the most advanced stuff we've learned so far.
 

Zoe

Member
The usual structure for those kinds of programs is

- prompt for first round of information and store in variables
- loop that contains all of the logic with the final line prompting the user to continue. The loop terminates when the user wants to quit

You never want to recall main.
 

wolfmat

Confirmed Asshole
Minamu said:
I'm trying to make a dice throwing game and I can't figure out how to make my "account" I store my virtual money in persistent between matches so to speak.
Your account is a variable, and its scope determines whether or not its value persists after it's been altered in some while-loop.

So it should suffice if you declare the account variable outside of the scope of the whiles and fors you're talking about.
 

wolfmat

Confirmed Asshole
Here's a pseudocode outline:

Code:
declare account

main:
    set account to 100
    while account > 0
        <<code for a game's round, alter account as rules tell you to>>
    print "You done busted. You need to lie dow;"

Edit: Also, the returned value of main() is supposed to be an error code, nothing else.
 

Zeppu

Member
Minamu said:
I'm trying to make a dice throwing game and I can't figure out how to make my "account" I store my virtual money in persistent between matches so to speak. For the time being, I'm simply using return int main() when the game asks me if I want a rematch. And of course, resetting int main means that "account" goes back to 0 since the very first thing the program asks for is place a maximum of 5000 in a betting account, which I withdraw from with each bet I make). It's for a programming for dummies course so I don't have a ton of experience with this stuff :S

Code:
void main()
{
[INDENT]int wallet = 5000; // or your starting value
bool quit = false;

while (!quit && wallet != 0)
{
[INDENT]Play game? y/n?
if (y)
{
[INDENT]account -= costOfGame;
int winnings = play()
account += winnings;[/INDENT]
}
else
quit = true;[/INDENT]
}[/INDENT]
}
 

wolfmat

Confirmed Asshole
To find header files by name alone, their path has to be in the relevant search path.

For gcc, for instance, there's default include paths and a flag to add new include paths.

So basically, if you know what's supposed to build your program, then find out where it gets its search paths from and fix them and your headers will be found. Well, or alternatively, if your headers are at a nonsensical location, then fix that.
 

Relix

he's Virgin Tight™
Chichikov said:
Try putting a fully qualified path there.
It's obviously not a long term solution, but it should get you going.

Yes this worked, but as soon as I compile it then tells me it can't find the includes are are inside iostream :lol :lol

Program is nice and all but.. meh =P. Will stick to Visual C++.

NOW! I know Basic (Intermediate level at least) and I wanna jump to C++. I also want to make a shitty 2D demo thingie just for fun and learning DirectDraw/SDL etc. GameDev has some tutorials but I easily get lost in the shuffle. Is there a specific guide/book you guys would recommend to me?
poweld said:
Please stop wasting everybody's time and get a IDE that is known, i.e. Visual Studio Express.

Sorry if this seems harsh, I just don't see the point in your using something nobody's ever heard of and then asking for help.

Erm... if you read right you would see I have Visual Studio installed but wanted to test something else to get out of the comfort zone.
 

wolfmat

Confirmed Asshole
Relix said:
NOW! I know Basic (Intermediate level at least) and I wanna jump to C++. I also want to make a shitty 2D demo thingie just for fun and learning DirectDraw/SDL etc. GameDev has some tutorials but I easily get lost in the shuffle. Is there a specific guide/book you guys would recommend to me?
For OpenGL, a lot of people start here: http://nehe.gamedev.net/

There's some wonky stuff in there, but it gets the job done for the most part, which of course is introducing you to concepts in OpenGL. To advance from that, I recommend getting the Redbook and the GLSL one.

As for SDL, the site should be good enough since there's a lot of documentation over there: http://www.libsdl.org/
 

Chichikov

Member
Relix said:
NOW! I know Basic (Intermediate level at least) and I wanna jump to C++. I also want to make a shitty 2D demo thingie just for fun and learning DirectDraw/SDL etc. GameDev has some tutorials but I easily get lost in the shuffle. Is there a specific guide/book you guys would recommend to me?
I really don't think that Direct2D is a great way to learn C++.
Learn the language through some simpler (and more C++-ish) project, and once you get comfortable with it, move to D2D.
Not to mention that you probably wants to get some familiarization with windows programming in general first (though you might already have it through different languages).
 

Zoe

Member
Relix said:
Erm... if you read right you would see I have Visual Studio installed but wanted to test something else to get out of the comfort zone.

If you really want to get out of your comfort zone, go gcc.
 

Chichikov

Member
wmat said:
Direct2D generally sucks. This draws a rectangle: Sample
Not everything that's not super-easy to use sucks.
Direct2D is not designed to do hello world type applications.

Don't get me wrong, there's plenty of stuff that can be improved with it, but that level of control and complexity is by design and is needed.
 

wolfmat

Confirmed Asshole
Chichikov said:
Not everything that's not super-easy to use sucks.
Direct2D is not designed to do hello world type applications.

Don't get me wrong, there's plenty of stuff that can be improved with it, but that level of control and complexity is by design and is needed.
Yeah, I heard that argument a number of times. I'd still like to see an example where its structure is used advantageously though. It makes the impression of being more of a hindrance.

I'm not saying "super-easy", but D2D does a lot of things that D3D already does, so that kinda defeats the purpose in huge sections of it. For instance, the device handling in there. It's just an irritating amount of resource management.
 

Relix

he's Virgin Tight™
Yeah GCC Compiler seems a bit too much :lol

We need an Official Programming Thread, this is the second time I hijack this thread and I feel bad =P. Thanks for the tips guys, will look into them :D

Edit: hey that OpenGL site, though a bit outdated, is pretty good =O
 

deadbeef

Member
Relix said:
Yeah GCC Compiler seems a bit too much :lol

We need an Official Programming Thread, this is the second time I hijack this thread and I feel bad =P. Thanks for the tips guys, will look into them :D


gcc is pretty much the standard. It's really not that difficult to get started with and figure out.
 

Chichikov

Member
wmat said:
Yeah, I heard that argument a number of times. I'd still like to see an example where its structure is used advantageously though. It makes the impression of being more of a hindrance.

I'm not saying "super-easy", but D2D does a lot of things that D3D already does, so that kinda defeats the purpose in huge sections of it. For instance, the device handling in there. It's just an irritating amount of resource management.
Oh, I didn't realize that was a D3D vs D2D argument.
To be honest, I wouldn't know.
I haven't been doing DirectX programming in a while, and I'm sure the technology changed quite a bit.

But in the context of this discussion it shouldn't matter, D3D is equally bad technology to learn C++ through.
 

wolfmat

Confirmed Asshole
Chichikov said:
Oh, I didn't realize that was a D3D vs D2D argument.
To be honest, I wouldn't know.
I haven't been doing DirectX programming in a while, and I'm sure the technology changed quite a bit.

But in the context of this discussion it shouldn't matter, D3D is equally bad technology to learn C++ through.
Fair point. C++ should be viewed as an object-oriented enhancement to C as a beginner, so that's where you want to start out.

Usually, beginner lections are stuff like "implement an ATM with accounts and the necessary operations to get money as a customer" or whatever. So do that first to learn what the point of OOP is.
 

PistolGrip

sex vacation in Guam
More C++ Questions (and C/unix questions) from a Java developer:

* When you get exceptions, how do you guys easily trace where that exception comes from. Unlike Java I get hex locations to memory instead of source code lines. Is this just the code was compiled with non debugging info?

* Do any of you debug remotely? Are there free remote debuggers out there.

* how does dynamic loading of a library really work. when I load with dlopen does the Operating System then keep the code somewhere in memory and if another request is made, it uses the same code?

EDIT: Apparently it does

* what preferred tools do you use to debug, code in a unix environment. Currently I am using netbeans (with jVi plugin) along with its debugger which is fantastic and free. intelliJ for Java is untouchable though :(

* I hear there is a way to get a stack trace of a process while its running without a debugger. How do you do this? Some people did this at work and were able to find a problem even though the process was still running and the trace did not affect the process. I think they were able to attach to the process and look the trace of a threa.

EDIT:Found it, its called strace!

Im sure a some major googling could answer these questions for me but I figure I join the conversation and support for a programming thread.

Also, what were the toughest Interview questions you were ever given?
 
I can't find a good reference for operator overloading. In particular one with good coding standards eg. labelling variables clearly and using it in a variety of settings.

My friend help me get it working (I was trying to overload an object with an array inside without dereferencing the pointer). Muchly appreciated. For such a simple concept the syntax has been a total bitch.
 

PistolGrip

sex vacation in Guam
Visualante said:
I can't find a good reference for operator overloading. In particular one with good coding standards eg. labelling variables clearly and using it in a variety of settings.

My friend help me get it working (I was trying to overload an object with an array inside without dereferencing the pointer). Muchly appreciated. For such a simple concept the syntax has been a total bitch.
Can you post an example? I am somewhat confused about your question.

Here is a nice guide
http://www.cs.caltech.edu/courses/cs11/material/cpp/donnie/cpp-ops.html
 
Status
Not open for further replies.
Top Bottom