Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The class declarations should indeed be in the header files; but the implementations ought to be in a separate source file. so, given your code, you would have this part in the header:

`

class personType
{
public:
    personType();
    void print();
    string firstname;
    string lastname;
};

but this part would be in a source file:

personType::personType(){}

just like with the print() method, which you would need to include in your solution/project.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Well, the good news is, you seem to have most of it done. Aside from the input issue, what did you need help with?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You will need to you double indirection, i.e., a pointer to a pointer.

#include<stdio.h>

void swap(char **a,char **b);

int main()
{
    char *p[2]={"hello","good morning"};
    swap(&p[0],&p[1]);
    printf("%s %s",p[0],p[1]);
    return 0;
}

void swap(char **a,char **b)
{
    char *t;
    t = *a;
    *a = *b;
    *b = t;
}

Not entirely obvious, but simple enough once you see it.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What have you got so far?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you explain a bit more about what you need? It isn't enitrely clear what sort of help you are looking for.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, this is a very peculiar way to do this, but if that's the assignment, there's nothing to be done for it.

I take that back. It's a ridiculous way to do it. Are you certain that you're supposed to have three different matrices in a single object? Normally, I would assume that what is desired is to have each object represent a single matrix, with the multiplication method taking a Matrix as an argument. doing it this way is absurdly limiting, and simply bad design.

If I were in a course where a professor handed out this assignment, I would walk out, because the instructor obviously doesn't know how to write object-oriented programs.

I suspect, however, that there's a simple miscommunication involved. I don't normally ask this, but could you post the exact assignment for us?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I was also able (after a horrible amount of effort for such a small project) to get it working entirely. It was a completely re-written versions, with hardly anything resembling the original code, however.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ugh, sorry, I didn't explain things very well; I had been in a bit of a rush earlier, and had to finish up before I could explain what I was suggesting.

The idea here is that you would use the header declarations as given here to begin re-writing part of you existing code, to eliminate some redundancies and smooth out the handling of the screen. The Screen class is a represntation of the screen itself; a Screen object holds not only the screen buffer, but the dimensions of the screen, and the current cursor position on the screen. This would actually be only the beginning of the class; in fact, I've changed my mind about DrawASCIICharacter() again, I now think you should make it a method of class Screen. You would use a separate method, let's call it gotoxy() for simplicity's sake, and you would use that to re-position the cursor before calling This let's you separate the

#pragma once

#include <exception>
#include <windows.h>


class ScreenCoordinatesOutOfBoundsException: public exception
{
private:
    unsigned int coordinate;

    ScreenCoordinatesOutOfBoundsException(unsigned int coord): coordinate(coord) {return;};

    virtual const int what() const throw()
    {
        return coordinate;
    }
};

class Screen 
{
private:
    CHAR_INFO* buffer;
    unsigned int width, height;
    unsigned int curr_x, curr_y;

public:
    Screen(unsigned int w, unsigned int h) width(w), height(h)
    {
        buffer = new CHAR_INFO[w][h];
    }

    ~Screen()
    {
        delete buffer;
    }

    unsigned int getWidth()  { return width; };
    unsigned int getHeight() { return height; };
    unsigned int getX() { return curr_x; };
    unsigned int getY() { return …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

That's just what A Haunted Army means, I think. By hard-wiring the maze into the code, it makes it difficult to change or reuse the code; it would make more sense to use a either a dynamic array or a std::vector< std::vector<char> > to hold the map data, and read the data itself in from a file. Using a vector of vectors would have the advantage that it would automatically track the dimensions of the map for you.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

By weird, what exactly do you mean? The backgrounds on both appear to be gray, is that what you are referring to?

If I were you, I would reconsider my design, and specifically, I would want to have some sort of parent GameObject class which the other elements could inherit the common code and constants from. As it is, you are reproducing several constants and the entire DrawASCIICharacter() method, which is something OOP design should help you avoid.

Actually, I would make DrawASCIICharacter() a standalone function, anyway, as it is useful even without reference to any specific object. The following header files should do nicely:

screen.h:

class Screen 
{
private:
    WORD* buffer;
    int width, height;
    int curr_x, curr_y;

public:
    Screen(int w, int h) width(w), height(h)
    {
        return;
    }

    int getWidth()  { return width; };
    int getHeight() { return height; };
    int getX() { return curr_x; };
    int getY() { return curr_y; };        
}

game.h:

#pragma once
#include <windows.h>
#include <process.h>
#include "screen.h"

//Constant Global Variables
const int WIDTH = 45;
const int HEIGHT = 30;

const WORD BACKGROUND_COLOR = 0;
const WORD BACKGROUND_COLOR_WIN = BACKGROUND_BLUE | BACKGROUND_INTENSITY;
const WORD PERSON_COLOR = FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_BLUE | BACKGROUND_COLOR;
const WORD END_COLOR = FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_GREEN | BACKGROUND_COLOR;
const WORD KEY_COLOR = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | BACKGROUND_COLOR;
const WORD DOOR_COLOR = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_RED | BACKGROUND_COLOR;
const WORD WALL_COLOR = FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
const WORD MAZE_COLOR = FOREGROUND_INTENSITY …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, though I would consider this: It only took me about four hours to re-write the code to use classes for the whole program, including the changes to the event handling and the movement. More importantly, I wrote the base class for all the game objects in about 20 minutes, and then extended that for the Player class in most of the rest of that time (that being the most complex of the classes). Once I had that, the Enemy class took about 10 minutes, because the majority of it was already present in the parent class.

I know it would take longer for you, since you aren't familiar with classes, but I assure you, they would end up saving you a lot of headaches, time, and effort.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It isn't necessary, but yes, I would recommend it, as Eclipse is a good IDE for Java and there are add-ons specifically for making it effective with Android development.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Try this tutorial on the subject; while the references to specific architectures is a bit dated, it is nonetheless generally accurate.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you should know general Java programming, as Android is based on Java. I would start with Oracle's Java Documentation, and a good book on the topic such as Thinking In Java (if you can't afford the e-book, the previous edition is available for free). You will also want to pick up the Eclipse IDE and learn how to use it, as it is the best suited for Android development.

Once you've got a decent grasp of the basics of Java programming, then you'd want to pick up the Android SDK, for developing your apps, and set up the Android emulator, for testing them. I would also recommend reading Learning Android as aan introductory textbook, followed by Programming Android in the same series.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The main issue is actually with your format string; for month, you should use capitalized letter M. Similarly, for 24-hour time going from 00 to 23, you need to use capital H. To get the time zone in the format you want, use the capital letter Z twice.

"MM.dd.yyyy HH:mm:ss ZZ"
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

More importantly, what newline() function? Python doesn't have one, AFAIK. To print a newline, you use print() with no arguments.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

One thing I would recommend also: you don't need to read the image files each time you want to change the image or BLIT it; you can save the images in variables and simply copy it to the current variable when you need to. In my version, I have it initialize the master cpoies at the time when the class is built, and then simply pass a reference to it to each of the individual objects, The relevant part of the Enemy class, for example, is

class Enemy(GameObject):
    front_src = "Boss.png"

    def __init__(self, screen):
        try:
            front = pygame.image.load(Enemy.front_src)
        except:
            print("Could not load enemy image")
            exit(-1)

The object in front is passed to the c'tor of the parent GameObject class, which stores it for later use. It uses a little more memory, but cuts down on the disk accesses, making the game more efficient. The Player class extends this with image_right and image_left members:

    def __init__(self, screen):
        try:
            front = pygame.image.load(Player.front_src)
        except:
            print("Could not load player front image")
            exit(-1)
        try:
            self.image_left = pygame.image.load(Player.left_src)
        except:
            print("Could not load player left image")
            exit(-1)
        try:
            self.image_right = pygame.image.load(Player.right_src)
        except:
            print("Could not load player right image")
            exit(-1)

        new_y = screen.get_rect().bottom - front.get_rect().top

        GameObject.__init__(self, screen, front, 0, new_y, 0, 0, False)

Even without using classes, you can simply have (for example) Player_front_img, Player_right_img and Player_left_img variables holding the image data, without having to read the file every time.

Necrozze commented: That's a really great tip actually, will deffinetly use it! Didn't think of it that way +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Rather than the standard Python time methods, I would recommend using a PyGame Clock object, as the Clock.tick() method is specifically designed for this sort of thing.

I would also take the time out to re-write the code with classes. My own version of this now has a GameObject class and a Player class; I haven't gotten around to the Boss and Bullet classes, yet.

(Is it wrong of me to have completely refactored this program for my own edification?)

chris.stout commented: Clock.tick() is perfect for what's needed here. +2
Necrozze commented: I changed to Clock.tick and now it doesent crash, thanks man +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is a grave breach of academic ethics on your part, and actually doing so would be an even bigger breach on ours (not …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Perhaps you could use some additional expalantions on variables, objects, functions, methods and classes.

An object is a set of properties and the set of actions which can be applied to those properties. For example, 17 is an object, representing the number seventeen. The string 'hello, world!' is also an object. The list [23] is an object that contains another object, and has the properties of length (one) and contents (23). A TkInter Label is an object with several properties, such as it's text, it's size, and it's position on the Frame. The properties of compound objects such as a Label are themselves objects.

A variable is a reference to (that is to say, a name for) an object. All variables in Python refer to objects. A variable can be changed so that it refers to a different object; for example, you could assign fnord to have a value of 5, then reassign it to a value of 17. The object 5 is still in memory though, and will remain in memory until all references to it are gone.

A function is a special kind of variable that represents a series of actions. A function can take a series of parameters, which are variables which, when the function is called, or run, are bound to the actual arguments of the function. A function can also return a value. An example of a function would be:

def foo(a, b):
    return a * b

which is then called like so:

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oh , you used classes ;)

Er, only in the technical sense that TkInter is all built around classes. I didn't define any class of my own here.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
  • Develop an extension of the ELF object format and the Unix ld linker that allows for C++ template functions to be separately compiled. Kudos if you can fit the extension into the existing format without changing the underlying structures, such that existing linkers can still use the extended format when the extensions aren't being applied.

  • Make up a toy language of some sort with some feature you've always found missing in other languages. Write a simple compiler or interpreter for the language. Defend the addition of the new feature with example code and statistical analysis of its performance and impact on the length of programs.

  • Develop a modified Clipboard/kill-ring with multiple levels of undo, such that users can visually choose which changes to recall from a history of previous alterations.

  • Develop a Linux or FreeBSD variant with system-wide garbage collection, integrated into the paging system. Provide analysis of the impact on both performance and security.

  • Develop a workable model of persistence and objects in untyped lambda calculus.

  • Develop a proof (or disproof) for the Church-Turing Thesis.

Evil minded, you say? Why, thank you.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oops, that should have been

        DrawASCIICharacter(count, yStart, text[count], CharAttribute);

Apparently, I'm getting confused between languages. This is what happens when you post at 3AM, I guess.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Just as an aside, you can remove the #includes for <stdio.h> and <stdlib.h>; you never use <stdio.h>, and <stdlib.h> is the C version of <cstdlib>. Just something I figured I would point out.

Given the number of places where you are writing out a series of characters on a given line in a given color, I would recommend a function like this:

int DrawString(int xStart, int yStart, string text, WORD CharAttribute)
{
    int count;
    int len = text.length();

    for (count = xStart; count < xStart + len; count++)
    {
        DrawASCIICharacter(count, yStart, text.CharAt(count), CharAttribute);
    }

    return count;
}

You will need to #include <string> in order to use this code as it is written. For characters that are normally non-printing, you could use the backslash+numeric code approach:

DrawString(19, 21, "\002 = You", PERSON_COLOR);
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, first off, you are making one of the classic mistakes mew C++ programmers make: putting the implementation of non-template classes inside the header file. Header files ought to have only global declarations, class and struct definitions, and preprocessor directives (templates are an exception to this, because of the limitations of most linkers and object formats). You will want to move the actual function implementations into separate files in the same project, and let them get compiled separated and linked in at build time.

Second. I think you've misunderstood the rules about default c'tors. If a class has no declared constructor, then the compiler will generate one for it; if, on the other hand, it has one or more non-default c'tors, then there must also be a declared default c'tor for the default c'tor to be built. If the class doesn't use an explict constructor, then it doesn't need to have a declared constructor, period.

Third, if you do declare a constructor, and it is relatively short, it should be possible to implement it inline, in the class definition, like so:

class personType
{
public:
    personType()
    {
        return;
    };
    void print();
    string firstname;
    string lastname;
};

This should get inlined just like the other inline methods.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If want you want is to have the cursor change to the hand cursor when you mouse over the label, then the following should work:

from tkinter import Tk, Frame, Label


def label1_lclick(event):
    print ("clicked at {},{}".format(event.x, event.y))

def label1_mouseover(event):
    master.config(cursor="hand2")

def label1_mouseexit(event):
    master.config(cursor='')


if __name__ == "__main__":
    master = Tk()


    mainFrame = Frame(master, height=500, width=300)

    label1dep = Label(mainFrame, text="Departement Informatique" ,bg = "blue" ,font=("times",12, "bold"),  fg = "white" )
    label1dep.place (x=40 , y=220)

    label1dep.bind("<Button-1>", label1_lclick)
    label1dep.bind("<Enter>", label1_mouseover)
    label1dep.bind("<Leave>", label1_mouseexit)

    mainFrame.pack()

    master.mainloop()

Let me know if that's what you wanted or not.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'm not sure I understand; where is the issue? Is it that you want to switch the mouse pointer when it is over the button, or is there an issue with the callback() function you currently have?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Certainly, I'd be willing to help out any way I could (short of doing the work for you, of course).

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

What sepp2k says is correct, but I suspect that there is more to this that may be relevant. What is the script supposed to do, and how many different codes are there? If there are more than two or three different ones, you may want to use a dictionary to hold the possible key-value pairs, and do a lookup rather than having an extended if/elif/else block. For example:

from sys import exit, argv

if len(argv) < 4:
   print("You must provide exactly three arguments for this program.")
   exit(-1)

code = argv[1]
phone = argv[2]
message = argv[3]

lookup = {'949': '62000001760', '947': '62000001840'}

try:
    servId = lookup[code]
except KeyError:
    servId='90928'

print servId
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hmmn, OK, so that's understandable. I would recommend that you try to take some time out to learn about them, however, if at all possible. Not only are classes and objects powerful tools, they are key concepts in Python, and heavily used in TKInter. In Python, all of the datatypes - numbers, strings, lists, tuples, dictionaries, etc. - are actually classes, and all the types defined by TKInter (e.g., Labels, Buttons, etc.) are as well. TKInter really expects you to define sub-classes to inherit from certain their classes (e.g., Frame) in order to make use of them.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As an aside, I have two comments to make. First off, while indent style is largely a matter of personal preference, it is a good idea to adopt some form of indentation and use it consistently. It is important for readability, especially as programs grow longer; and while it may not seem like it now, it is crucial that you get into the habit of seeing programs as something other coders will have to be able to read at some point in the future. To this end, here is your program re-indented (using AStyle and EMACS) in Allman style:

#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
#include <fstream>
#include <C:\\Users\\N.\\Desktop\\Popcorn\\Popcorn\\JJ.cpp>

using namespace std;

int main()
{
    fstream InFile;
    string Name;
    int Jars;
    double Acres;

    PrintHeader();

    InFile.open("C:\\Users\\N.\\Desktop\\Popcorn\\Popcorn\\JJ.cpp", ios::in);

    if (!InFile)
    {
    cout << "Can't Open the input file.";
    return 1;
    }

    while (!InFile.eof())
    {

    GetData(InFile, Name, Acres, Jars);
    }

    InFile.close();
    cin.get();
    return 0;
}


void PrintHeader(void)
{
    cout << setw(23) << "Pop CoOp" << endl;
    cout << "Farm Name" << setw(30) << "Production" << endl;
    cout << setw(41) << "Thousands of" << endl;
    cout << setw(47) << "Pint Jars per Acre" << endl;
    cout << setw(53) << " 1 2 3 4 5 6" << endl;
    cout << setw(52) << "---|---|---|---|---|---" << endl;
}


void GetData(fstream& In, string& Name, double& Acres, int& Jars)
{
    char x=' ';
    int count = 0;
    In.get(x);
    while (x < 29 || x != ',' )
    {
    Name = Name + x; …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You are welcome, I am glad that I was able to help. Were you able to get it working?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, in that case... actually, you're quite close to it, as it happens. You simply want to have another print line to print a hash before the inner loop, and change the print inside the loop to printing a space:

NUM_STEPS = 6
def main():
    for r in range(NUM_STEPS):
        print ('#',end='')
        for c in range (r):
            print (' ',end='')
        print('#')

main()
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hmmn, we'll need to know whether it is overflowing or underflowing the test, then. Try replacing

printf("constraint violated");

with this:

printf("\n\tconstraint violated: ");
if (fill_s[0] < fsi)
{
    printf("underflow, %d < %d\n", fill_s[0], fsi));
}
else if (fill_s[0] > fsf)
{ 
    printf("overflow, %d > %d\n", fill_s[0], fsf));
}
else
{
    printf("unknown error, program halting.\n");
    system("pause");
    exit(-1);   
}

That will at least tell you more about the problem.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Test what, our patience? Seriously, even if anyone here were inclined to simply provide code to you - which we are not - you would need to give a lot more detail about what you need.

One of the forum rules states that, when posting for help with a program, you must demonstrate due diligence - you need to show that you have made a good-faith effort to solve the problem yourself, and that you have reached an impasse you can't reslove. In other words, show us your code. If you don't have any code to show us, tell us what you need help in doing. Make an effort first, before asking for a hand-out.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, Let's trace that value backwards... fill_s[0] is ten to the power of xdd; xdd is the inverse of xd ; xd is the one minus pd_fill_n... where does the value of pd_fill_n come from?

I can only assume that pd_fill_n is a global, as it isn't declared in the code shown here. Is pd_fill_n initialized? if it isn't, then if your are lucky, the compiler is setting it to zero. More likely, it contains whatever garbage happens to be on the stack where the variable is stored. To fix fill_s, make sure that pd_fill_n has the correct value set.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, now, I have done some major surgery on the bhpeqns() function - purely refactoring, mind you, it should give more or less the same results as before - which should make fixing and maintaining the code much, much easier. In the process, I've managed to cut the number of local variables in the function by about 2/3rds. If I actually understood the code better, I could probably do more still. :)

The two major realizations which made this possible were the observations that several of the variables were for the same values, but in metric and US units, of which many were for either the intake valve or the outflow valve. By defining a struct type, I was able to combine the first group into single variables; by changing the second ones to arrays, with defined indices for the INLET and OUTLET; I was able to combine the latter. In many cases, both applied, so I was able to replace four separate variables with a single composite variable.

Note that I systematically used double rather than float, as you get significant improvements in the calculations' precision this way.

You will also be pleasantly surprised by the way I have simplified the calculations for lg, KAV1 and KAV2, I think.

I think that you would do well to adopt this version of the function, as it should be much easier to understand once you've grasped the way I've organized the variables, and much easier to fix any problems that may …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

One thing that doesn't seem to have been mentioned is that namespaces are less for projects by a single individual, than they are for integrating disparate libraries and projects by different groups of developers. While namespaces are a boon to a single programmer, they are a necessity to developers working with other people's code, where they need to avoid conflicts between programs written without consideration for whether another programmer has used the same class name.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I think what is happening is this: in the hooke() function as written, the first call to bhpeqns() uses the default parameters of (0.6096, 12.0). The second call then uses the parameters input by the user, which in this case are (1.0, 12.0). This second set of values seems to cause bhpeqns() to blow up. Since 1.0 is more or less in the middle of the range for the fh values, this should not be the case.

I'll keep investigating this as best as I can, but I'll be out of town most of today and tomorrow; I probably won't be able to get back to you until the day after tomorrow. Sorry.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've checked it out, and the problem (or at least one problem) is indeed in bhpeqns(). On the second call to the function, it goes into an infinite loop in the first do/while() loop. Apparently, the input values for bhpeqns() on the second pass are out of bounds.

BTW, you are a) still using void main(), despite the fact that I said it was incorrect, and b) still using short variable names that don't help describe their purpose. This isn't Fortran 77, you aren't limited to 6 character variable names! Even Turbo C++ let's you use 32 character variables, so there is no good reason to limit yourself to these pitiful, cryptic abbreviations.

Oh, and there's still no reason to have the vapor pressure, humidity and enthalpy calculations inside of the first do/while() loop, as there is nothing in the loop that affects them. You can and should extract that whole section of code and move it to before the beginning of that loop. Even if you insist on using separate variables rather than arrays for them, you can at least do that much.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

kindly help me with the code

Difficult, given that the code as posted doesn't compile (at least not under GCC). I'll do what I can, but you can expect that a lot of changes will be needed.

Are you certain that the bhpeqns() function is correct? I'd hate to be fixing the wrong thing...

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've been working on this most of the morning, and have at least re-organized some aspects of it into something that should be reasonable; unfortunately, the results I get are anything but. One of the figures is overflowing right at the start, and this is throwing off the whole program. Perhaps you can use what I've done to make the program fit the data better.

hooke-jeeves-test.c

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <stdbool.h>
#include "hooke-jeeves.h"


#define VARS (250)
#define RHO (0.85)
#define EPSILON (0.0001)
#define ITERMAX (1024)
#define NVARS (2)


bool initialize_plant_state(FILE* data_src);

double bhpeqns(double x[], int n, const int vars);

double saturation_vapor_pressure(double twbi);
double sp_humidity(double d, double w, double svp);
double enthalpy_metric(double d, double humid);
double enthalpy_btu(double enthalpy);


// global 'constants' to be set in initialize_plant_state() -
// they vary with the initial data set, but are not altered during the
// program run

double thw, tcw, twbi_init, tdbi, fand, hubd, fann;
double aih, cell, celw, gpm;
int ais, celn;
double to, t9;
double vapor[7];
struct
{
    double hum1, hum2, po, c;
} humidity;

double spec2, spec3, spelo, spvolro;
int wlmin, wlmax, vmin, vmax;


// global variables - these are set in the functions
double app, r;
double aia, edisa, cela, gpmpc, wl;


int main()
{
    double startpt[VARS], endpt[VARS];
    int i, jj;

    char filename[FILENAME_MAX];
    FILE* data_src;
    bool success;

    printf("Enter the name of the data file: ");
    scanf("%4095s", filename);
    data_src = fopen(filename, "r");

    if (data_src == NULL)
    {
        printf("Unable to open file '%s', exiting.\n", filename);
        exit(1);
    }

    success …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would recommend moving the initialization data into a file to be loaded at runtime; this would allow you to have different starting values for the plant's state variables, without having to alter the compiled program. You can have different files containing different starting values to get the variance you need.

While I dislike having so many global variables, I don't see any alternative, as there is no clear way to pass so many values to the function without either an unreasonably large number of parameters, or lumping them all together in a massive struct. As it is, the best we can hope for is to rein in the chaos by putting related values together into arrays and structs, and even then, I don't know enough about the data sets to give meaningful names and develop useable groupings to all the data.

I have managed to pull together some other functions, and at least one useable structure, but I don't know how helpful these will be to you. Note that I have been using double variables rather than floats, to get higher precision; I would recommend you do the same throughout the program.

struct
{
    double hum1, hum2, po, c;
} humidity;


double sp_humidity(double d, double w, double svp)
{
    double sphua, sphub, sphud;

    sphua = humidity.hum1 / humidity.hum2;
    sphub = humidity.po * humidity.c * (d - w);
    sphud = svp - sphub;
    return (sphua * sphud) / (humidity.po - sphud); // sp humidity is calculated
}


double enthalpy_metric(double …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

When you say you were expected to vary the results, do you mean you would set them in the program differently and recompile and run it, or that you would need to be able to enter in the data from somewhere (presumably a data file - entering all that in by hand would be certain to result in frequent errors) and pass the data to the functions? I ask this because as things are, you are basically treating the initialized values as constants - they never get reassigned at any point - which is why I thought they might be constants in the program.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

gather related values up into arrays or structures wherever possible.

I forgot to give an example of what I meant by this. What I meant was, that instead of something like this:

float svpa = -2948.997118, svpb = -2.1836674, svpc = -0.000150474,svpd = -0.0303738468;
float svpe = 0.00042873, svpf = 4.76955,svpg = 25.83220018;

use this:

float vapor[] = {-2948.997118, -2.1836674, -0.000150474, -0.0303738468, 0.00042873, 4.76955, 5.83220018};

or this:

struct VAPOR 
{
    float a, b, c, d, e, f, g;
} vapor = {-2948.997118, -2.1836674, -0.000150474, -0.0303738468, 0.00042873, 4.76955, 5.83220018};

It helps organize the values a little better.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ah, DosBox isn't a compiler, it is a utility that allows you to run 16-bit programs (e.g., Turbo C++) in a modern Windows environment. I will assume that it is the Turbo compiler, then, or something from the same time period (c. 1990).

This could present a problem, as it is possible that you are getting an overflow (or an underflow) somewhere, and it isn't getting detected. I don't know if that's the case, but it may be, which case I'm not sure what you can do about it other than getting a newer compiler.

BTW, is this supposed to be in C, or C++? You use C++ style comments in several places, which most C compilers won't accept unless they support the newest language standard; yet you aren't using any C++ functions or operators. Just wondering.

Addressing the code isues, I again want to stress dividing the bhpeqns() function up into smaller functions. As it is, it sprawls over 370 LOC, and contains well over 100 discrete variables. This is simply unmanageable. If you want any chance of getting this to work, start breaking the sections of code up into functions, like so:

float saturation_vapor_pressure(float vapor[], float twbi, float to, float t9)
{
    float too, saturation[7];

    too = twbi + to;
    saturation[0] = vapor[0] / too;
    saturation[1] = vapor[1] * log(too);
    saturation[2] = vapor[2] * (twbi - 0.01);
    saturation[3] = vapor[3] * pow(10, saturation[3]);
    saturation[4] = vapor[4] * (1 - (t9 / too));
    saturation[5] = vapor[5] * pow(10, …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's try this again, shall we?

def temperature():
    temp = None
    coldPoint = 21
    hotPoint = 24

    while temp is None:
        try:
            temp = int(raw_input("Enter temperature: "))
        except ValueError:
            print("Ooops! Enter number Please !")

    print "The temperature is",

    if temp <= coldPoint:
        print "too cold."
    elif temp >= hotPoint:
        print "too hot."
    else:
        print "acceptable."

if __name__ == "__main__":
    temperature()
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Using the input() function in Python 2.x is generally considered a bad idea, as it will actually evaluate the statement as if it were a line of Python code. This leaves a large security hole that anyone could exploit - if,instead of just a number, the user were to enter something like;

os.chdir('/')

they could play merry hell with the program and/or the operating system. Using raw_input() and then casting to int is generally the safest way to read an integer value in.

In Python 3.x, the input() function has been changed to behave like raw_input() did in Python 2.x; i.e., it reads in a string of text without processing it.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you don't mind me asking, which compiler are you using? If it is Turbo C++ (or any other 16-bit compiler), there may be issues with the size of the int and float variables being used. If I recall correctly, Turbo C uses 16-bit int values and 32-bit floats.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Could you please post both your current code, and the problematic results? It would help if we were all looking at the same thing here.