No that is the best method in my opinion and its not very complex given that it only involves elementary school mathematics and lends itself easily to an iterative solution.
If you are using C why are you posting in C++?
No that is the best method in my opinion and its not very complex given that it only involves elementary school mathematics and lends itself easily to an iterative solution.
If you are using C why are you posting in C++?
You are missing a * on line 29
The logic is to store digits rather than the whole integer. then you do addition in the same way you used to do it when you where 10 years old, one column at a time.
Of course although you are storing digits you can choose the base to make effective use of your data type so rather than base 10 you could use something like base 65536 and use a 32bit int to store each digit.
You never call the constructor that takes parameters with "mark" "australian".
You never call the display()
method
Does it even compile?
main returns int not void returning void is undefined behaviour.
it is unlikely that it stores 0.2 as 0.259595 but it might store it as 0.2000001.
Remember that a float is 4 bytes, it has the same unique number of combinations as an int (4 bytes), that is 4294967296.
However a float can store "any" value in the range 1.175494351e-38F to 3.402823466e+38F either positive or negative. That covers a very large range of values. As a result a float only stores numbers to a specific precision (7 significant digits) and the value it stores should be treated as a approximation to the required value.
Normally this doesn't effect initialisation quite so much it only comes into play when doing calculations, try this for example
#include "stdio.h"
int main()
{
float f1 = 10000000.F;
float f2 = 0.F;
int x;
for( x=0; x<100; x++)
{
f1 += 0.9F;
f2 += 0.9F;
}
printf("%f %f\n", f1, f2);
return 0;
}
but you have initialised your float to a double constant (a float constant would be 0.2F
) so the compiler has had to do a conversion which may have introduced the errors.
If you need to compare 2 floats to a tolerance then ...
Firstly don't, try to design your software so you don't have to do that.
Secondly if you really can't avoid it then take the absolute value of the difference of the 2 values fabs(f1 - f2)
and test it against your tolerance using one of < <= > >=.
When editing you need to reposition the file pointer to the beginning of the record you just read before writing, otherwise you overwrite the next record in the file. You will need to use fseek to do this.
Additionally you program is leaking memory like a sieve, every time you call malloc you need to be calling free once you have finished with the memory to return it to the heap.
You mean that you don't know how to use cin to obtain user input to insert into your list or that you don't know how to insert data?
BTW Account::insertNode is a disaster that in most cases will cause your list to corrupt.
You appear to be trying to use TempBuffer to temporarily read a string before storing it. If you are reading a string from a file into a buffer how many dimensions does the buffer need?
When calling fgets it is a really bad idea to give the buffer size as bigger than the size of the buffer you are actually passing a pointer to.
How many line does this file contain? How many times does your code call fgets?
You are not checking the return value of fgets so you will continue trying to process the file even if an error occurs or the program gets to the end of the file.
Is array supposed to be an array of 100 strings or an array of an array of 100 strings (or colloquially are 2 dimensioned array of strings with both dimensions sized as 100)?
Have you run that?
It does not determine if a is prime, that is easy to tell because at no point is there a "a is prime" cout statement.
What it actually prints out is all the prime divisors of a.
That is of course ignoring the fact that you have main returning void so the entire program exhibits undefined behaviour because main always returns int.
If you have a fixed range to find prime numbers over, as in your case all primes below 100 another method is to create a list of all the numbers, 3,5,7,...97,99. Then you take each entry in the list in turn and remove all multiples of that value from the list. When you get to the end of the list the numbers that are left are all prime.
Then the thing to do is have a local char variable that you read the file into and then use a switch/if statement to decode the value into the actual value for employee[idx].pt
You have not provided enough information for us to help properly.
In Finance you have not indicated what the member data represents or how you would add 2 together 2 values.
In Test you have not provided the type definition so we don't even know the type of Test::mX
What you have supplied is so sketchy that there are no obvious errors in it.
Which line of your code reads the 19?
What do you do with that 19 after it has been read?
What will your code do if your professor decides to test it on a file containing 20 values?
@chiwawa10 you have miss-understood how std::find works and should be used and in fact you only have to look at the example in the page you have linked to to find the error.
The end pointer should be a pointer to the first location just passed the end of the array so for an array of any type T and size N
T array[N] = {};
T searchValue;
// Initialise array
std::find(array, array+N, searchValue);
std::find will return array+N if the value is not found or a pointer to one of the array elements if it is.
The problem is that there are lots of corner cases which is why you have to keep on recalculating number of trucks and expected average because you have to keep on adjusting your goal for what you have already done.
take this series of loads
10, 35, 15, 20, 10
On the first pass
Total load = 10 + 35 + 15 + 20 + 10 = 90
Trucks = 90 / 40 = 3 (rounded up)
Average Load = 90 / 3 = 30
Assign 10 to Truck 1, 35 wont fit into the truck so start pass 2
Pass 2
Total load = 35 + 15 + 20 + 10 = 80
Trucks = 80 / 40 = 2
Trucks has dropped by one calculation on track for 3 trucks
Average Load = 80 / 2 = 40
Assign 35 to truck 2, 15 wont fit in onto pass 3
Pass 3
Total load = 15 + 20 + 10 = 45
Trucks = 45 / 40 = 2 (rounded up)
Trucks has NOT dropped by one calculation not on track for 3 trucks however it is not possible to fit anything else into trucks 1 or 2 so we must actually be look for a 4 truck solution even though our initial estimate was 3
Average Load = 45 / 2 = 23 (rounding up)
Assign 15 to …
Sorry I had not fully realise the implication of rule 3. However I think something like this should work.
From the complete order list build a list of orders or work on. This sub list is bounded by any of the following conditions, the start and end of the main list, a split order. From the second example 18, 18, 8 would be a sub-list because it is bound at both ends by sub-lists.
Calculate the number of trucks required: (18 + 18 + 8) / 40 = 1.1 = 2 (because you can't have 0.1 of a truck)
Calculate the average load for each truck: (18 + 18 + 8) / 2 = 22
From the list fill the first truck until you are as close as possible to the average.
Truck 1: 18 because abs(22 - 18) < abs(22 - (18+18))
If there is 1 truck left put everything else into that truck
Truck 2: 18, 8
Else recalculate the new number of trucks and average.
If the number of trucks has not gone down by one then move up the stack of trucks until you can shift 1 load back into a previous truck. And restart.
Otherwise start filling the next truck.
I think you will need to do this recursively because I think there will always be possible load groupings that you will be unable to determine the correct layout for by a single pass. A Slightly tricking set of loads is
19, 20, 22, 24
I'll explain more if I get time later.
Actually prism does not need to be a template. What it needs to do is store a shape*
that points to a shape that is the cross section of the prism.
That would let you change the cross section if you wanted to.
Note that this pointer should probably point to a shape constructed specifically for use by the prism so that would need to be allocated on the heap.
Also when passing objects into functions always use either a constant reference const shape&
or if the object passed in is going to be modified a reference shape&
to avoid lots of copy constructor and destructor calling.
Also when initialising variables in a constructor where possible it is better to use a constructor initialisation list rather than assigning to them in constructor body. Again for classes this is more efficient because it calls a single constructor rather than calling the default constructor and the assignment operator.
So prism might want to look something like
class prism : public shape
{
private:
string type;
double depth;
shape* crosssection
public:
prism(double d, const square& cs)
: type("Prism"),
depth(d)
crosssection(new square(cs))
{
}
};
Note this prism only has a constructor for squares you would have 2 choices, either you write a constructor for every plan subclass of shape but that really is object orientated and is a pain and requires prism to alter every time a new plan shape is added so a better option is …
I do not think a bitset is going to be very useful to you. You will have to extract each bit out of the stream individually and put it in the bitset from what I see of its implementation.
I think you might be better off creating a Pixel class of your own based on a 16 bit integer data type that can be constructed from a 16 bit integer or 3 4 bit nibbles. Then use a vector to hold you class data.
You class would contain helpers to extract specific bits if you are really interested in them but that doesn't seem likely as the 12 bits actually represent a level/value.
Then you will need to write code to extract 12 bits at a time (or 3 4 bit nibbles) from you buffer of data.
Well the initial thing to do is see if you can write down or actually catty out the process on paper.
It needs to be something like
INITIALISE TRUCK LIST TO EMPTY
CURRENT TRUCK = NEW EMPTY TRUCK
FOR EACH ORDER
IF THE ORDER WILL FIT IN THE CURRENT TRUCK
PUT THE ORDER IN THE CURRENT TRUCK
ELSE
PUT THE CURRENT TRUCK ON THE TRUCK LIST
IF THE ORDER IS A SPLIT ORDER
CALCULATE THE TRUCKS IN THE SPLIT ORDER
PUT THE SPLIT ORDER TRUCKS ON THE TRUCK LIST
CURRENT TRUCK = NEW EMPTY TRUCK
ELSE
CURRENT TRUCK = NEW EMPTY TRUCK
PUT THE ORDER IN THE CURRENT TRUCK
ENDIF
ENDIF
END FOR EACH
IF THE CURRENT TRUCK IS NOT EMPTY
PUT THE CURRENT TRUCK ON THE TRUCK LIST
ENDIF
PRINT TRUCK LIST
Also I think your second example is wrong I think trucks 4 and 5 should read
Truck 4 holds: 18 18 for a total of 36
Truck 5 holds: 8
Once you can do the process on paper you stand a better chance of being able to write a program that will do it.
This comes down to my 3rd paragraph from my previous post.
Where is outfile declared that is visible in FRACTION.CPP? It is not declared in the file itself and it certainly isn't declared in fstream. FRACTION.H doesn't declared it or include a file that does. That only leaves StdAfx.h and since you are getting the error I assume it is not declared in there.
If you want to use outfile in Fraction::print then you will need to declare it somewhere that is visible to Fraction::print.
However I come back to my previous point, this is really poor programming style, it would be better to declare Fraction::print as
void Fraction::print(ostream& out) const
{
out<<numerator<<"/"<<denominator;
}
and pass outfile into print as a parameter.
Here is my error.
fraction.cpp(118) : error C2065: 'outfile' : undeclared identifier
If you had posted this instead of saying "this error" or said "this compiler error" the last 4 posts would not have been required. I thought you were dealing with a runtime error. Now do you see the importance of providing ALL the information you have.
Anyway, you are saying the error is in a piece of code that you have not posted? Does that really strike you as a good idea?
Is outfile declared in a place that is visible to Fraction.h? Remember in C++ that at any point you can only used what has already been seen in processing the file.
Anyway that is all beside the point, you should not be using global data, it completely breaks object encapsulation and is a maintenance nightmare. If infile is only used in main then declare it in main. In Fraction::print change it to accept a ostream&
as a parameter and print into that.
for(i=1;i<=3;i++)
{
for(j=1;j<=3;j++)
{
num = 1 + rand()%9;
grid[i][j] = num;
Nop that is an out of bounds data access, undefined behaviour and asking for a crash.
You did not read post #5 by abhimanipal closely enough.
Arrays are indexed from 0 if you declare an array with a size of 3, then valid indexes are 0, 1, 2
int array[3] = {};
int a;
a = array[0]; // Good
a = array[1]; // Good
a = array[2]; // Good
a = array[3]; // Bad - out of bounds access
Line 19 and 20 you open both files using open then at line 22 you use infile and at line 39 you use outfile.
At no point between calling open and using the objects do you test to make sure that the object is valid and the file is open.
Check your documentation of ifstream::open and ofstream::open for the failure cases.
Opps missed your comment another reason to post the entire message.
What are you doing trying to open and close an already open stream? out is a working output stream just use it.
Did you change the declaration of the function ArrayIntStorage::write as well as the definition?
If you are going to post warning messages post the entire message because the text often contains extra details, the line number can be useful and to anyone not familiar with the Microsoft compiler the number is completely meaningless.
You have = instead of == in your if statements.
You only ever call rand()
once.
You never initialise count.
Even if you could, which you can't because as someone as pointed out else where ostream might not be a file stream it could be any stream including one without a file name, but even if you could the open in your write function would fail on some operating systems because the file is already open.
I didn't say pass the file name I said pass the output stream.
Your write function would be declared
void ArrayIntStorage::write(ostream& out)
{
// Code to write to out
}
and you would call it as per line 15
Why don't you just pass ostream &out
into your write function and write to the provided stream?
As you have said bit fields are platform dependent. Data alignment is an issue and is also platform dependent but for the datapixel structure defined in terms of __int8 aka char it may well be able to align the structure on any byte boundary.
On many platforms structures are aligned at the largest alignment required for any of its members. A struct containing only char aligns at byte boundaries, a struct containing only short (2 byte int) and smaller aligns at 2 byte boundaries, a struct containing only long (4 byte int) and smaller aligns at 4 byte boundaries.
All data types have a size in bytes so the datapixel data type has a minimum of 4 padding bits. It may have 2 padding bytes as well if the compiler has decided to align the structure at 4 byte boundaries.
So the expression *(reinterpret_cast<datapixel*>(ptr)+idx) for values of idx != 0 will be skipping bits, the padding bits.
Bit fields are really just semantic magic for access the bits in an integer data field without resorting to using the bitwise operators. Since bit field implementation is platform dependent and bitwise operators are not conventional wisdom is to leave bit fields alone and use bitwise operators.
To extract data from a series of bytes (char * or void *) where the bit size of the fields you want to extract is != N*CHAR_BIT the only portable way to do it, in fact the way to do it …
No because the size of datapixel will be in bytes and a mutiple of whole bytes
If its not possible then just let me know. If you don't like the design that is a matter of taste and not really a help answer, But im sure sub classing is very useful and should be used more often if it is not.
Like I said, it is possible, your _get and _set structures need to have a constructor that takes and stores a reference to the parent object.
Actually not liking a design is not only "a matter taste". Some designs are just plan wrong and or foolish. That said there is certainly more than 1 good design to solve any problem.
You may think sub classing is very useful I on the other hand think you are creating a confusing and obfuscated mess.
However you may wish to look at the Bridge design pattern which does something a little similar.
C++ is completely thread unaware, it has no concept of threads, threading or the posibility that it might be in use. That is because multi-tasking/multi-threading is highly platform dependent.
The STL will not throw any exceptions specifically related to multi-threading being used in a program.
Accessing any kind of data in an unguarded manor from multiple threads can lead to inexplicable behaviour, undefined behaviour and ultimately system crashes. The STL containers are no exception to this.
Where you have them looks OK to me. What doesn't look OK is that you don't test to see if the files actually opened before trying to use them.
Calling scanf twice does not mean the user has to enter the data on more than one like. There is no implied reading of a new line character at the end of a scanf call.
scanf just requires whitespace between fields which is space, tab, newline, carriage return but it is not at all fussy about which ones it gets.
Windows has no synchronisation exception, nor have I every seen an OS that did.
If you share any data between 2 threads, including an std::string without guarding access to the data then you risk corrupting the data by simultaneous access which is likely to be bad for program execution.
I think you should probably expect an stl::container to throw any standard exception I do not think it is specified what they do and don't throw, probably because of the possibility of it being platform dependent.
my teacher told me that only one line must had to be changed in this code
here's my code:
I can only say I don't think he has properly looked at this code or you have not understood his reply (assuming you paraphrased it).
only this line he told me
printf("*");
and i made a research and learn about that:
printf("%5s", "*");
I can not see how you would alter printf to output the correct number of spaces which is variable only on the first iteration of the loop especially since the loop at line 14 destroys the data needed to actually calculate what the correct number of spaces are.
Try this delete (or comment out) lines 16 - 19 and preplace them with this code line
printf("Line %d: %d spaces followed by %d stars", LineNumber, numberSpaces, numberStars);
You will need the following declaration int LineNumber, numberSpaces, numberStars;
I leave you to put in the maths required to cacluate the correct values for each line.
Once you have worked out how to calculate the correct numbers for each line then you can think abouttrying to actually output the correct numbers of spaces and stars.
Well show us what your modified code and give a full description of how it is not working.
In my opinion you are making things overly complex and attempting to introducing a style that is likely to just confuse anyone else trying to use the code you write which ultimately results in more maintenance overhead for no actual gain in functionality over
#include <iostream>
using namespace std;
class C_User
{
public:
long getNumber( void );
void setNumber( void );
private:
long m_iNumber;
};
long C_User::getNumber( void )
{
return m_iNumber;
}
void C_User::setNumber( void )
{
cout << "Enter a number: ";
cin >> m_iNumber;
}
int main( int argc, char* args[] )
{
C_User User;
User.setNumber();
cout << "You entered: " << User.getNumber() << endl;
return EXIT_SUCCESS;
}
If you wanted to do this you would have to do something even more obfuscating like store a reference to the parent object in _Get and _Set and initialise them in the _Get and _Set constructors when a C_User object is constructed and use the reference to access the parent object data inside the methods of _Get and _Set.
It makes sense that you can not directly access the parent object data inside _Get and _Set methods because inside those methods this
refers to _Get and _Set instances respectively and not the parent class instance.
For what you need to do you can treat the pointer as an array, pointer[0] will work as if pointer was actually an array. Your definitions should look like this
double findMax(double array[], int size)
{
double max;
// Code here working on array and size to calculate max
return max;
}
Delete the array stock1, stock2 and stock3 from the inside of findMax instead do the same operations on array to calculate the maximum value in the array which you can then return.
When I said well placed cout statements I meant cout statements inside the operators printing out all the values involved in the calculation.
Try making c and int not a double. == and != really don't work well with double and float types because those types approximate values.
If you have a working == and a working > then >=, < and <= can be defined in terms of the other 2 and you have less code to maintain.
However line 16 single = and why not use >=?
Line 34 why not use <=?
Apart from that I see good reason why they aren't working so try debugging with some well placed cout statements
If they don't have the same denominator you can multiply denominator of the 2nd by numerator of the 1st and then denominator of the 1st by numerator of the 2nd. If denominator 2 times numerator 1 is larger than denominator 1 times numerator 2, then fraction 1 is the bigger of the two.
Yes but mathematically that is the equivalent of calculating the numerators of both fractions if they expressed with a denominator of (denominator 1 x denominator 2) my statement holds under the implied assumption (or at least I implied it given normal fraction mathematics) that given any number of fractions you can always find a common denominator which they can all be expressed in.
You can not compare fractions unless they have the same denominator. If they have the same denominator then you can simply compare the numerators.
You could mess around with scaling your integers so that you only produce the required number of decimal places or you could just use the io manipulators from <iomanip> to format the output of the double value to only show 2 decimal places cout << fixed << setprecision(2) << SemesterGpa << endl;
.
personally in this case I would probably do the second.
From you last listing it is the file name hard coded on line 16 of your program.
If you mean how do you avoid hard coding the file name then either request the file name from the user at the start of the program or let the user specify the file name to use on the command line. You can access command line parameters by writing main as int main(int argc, char* argv[])
, any book or reference should let about using argc (the number of parameters) and argp (an array of pointers to the parameters).
Note that argv[0] is a pointer to the actual executable name.
When you instantiate a derived class before calling the constructor of the derived class (TwoDayPackage) it calls the constructor of the parent class (Package). Unless otherwise told it calls the default constructor so
TwoDayPackage::TwoDayPackage(const string &sn, const string &saddress, const string &scity, const string &sstate, int szipcode, const string &rname, const string &raddress, const string &rcity, const string &rstate, int rzipcode, double wt, double shipCost, double f)
{
setSenderName(sn);
setSenderAddress (saddress);
setSenderCity(scity);
setSenderState(sstate);
setSenderZIP (szipcode);
setRecipientName(rname);
setRecipientAddress(raddress);
setRecipientCity(rcity);
setRecipientState(rstate);
setRecipientZIP(rzipcode);
setWeight(wt);
setCostPerOunce(shipCost);
setFlatfee(f);
}
is equivalent to
TwoDayPackage::TwoDayPackage(const string &sn, const string &saddress, const string &scity, const string &sstate, int szipcode, const string &rname, const string &raddress, const string &rcity, const string &rstate, int rzipcode, double wt, double shipCost, double f)
: Package()
{
setSenderName(sn);
setSenderAddress (saddress);
setSenderCity(scity);
setSenderState(sstate);
setSenderZIP (szipcode);
setRecipientName(rname);
setRecipientAddress(raddress);
setRecipientCity(rcity);
setRecipientState(rstate);
setRecipientZIP(rzipcode);
setWeight(wt);
setCostPerOunce(shipCost);
setFlatfee(f);
}
However Package has no default constructor, either you have to create a default constructor for the parent class or, and this is what I think you need to do, you put in a specific call to a non default constructor.
Additionally your derived class should not initialise/assign the members of the parent class and the parent class constructor should do that (unless it needs to override some values) so your derived constructor should be
TwoDayPackage::TwoDayPackage(const string &sn, const string &saddress, const string &scity, const string &sstate, int szipcode, const string &rname, const string &raddress, const string &rcity, const string &rstate, int rzipcode, double wt, double shipCost, …
double numerator, denominator;
Personally I would have made these int and made the entire class use int unless you really want to be able to do 2.5 / 3.2 type fractions (may be you do I don't know). ints process more quickly and do not suffer from the randomness of approximation that doubles do.
That is for ints 1 + 1 == 2 always buf or doubles you may sometimes find that 1.0 + 1.0 = 1.99999999999999
I didn't say clear size before closing the file I said clear size before reading the file.
Come on put some thought into it size has to be the number of records you just read so once if have finished reading a file you don't want to clear size because you will destroy that file. However as you come to read another file you want to start at the beginning of your array again and you want to start counting read records again so that you don't add to what was read from the last file; therefore before reading the file again you need to clear size.
You can do a minimum search as recursion. Basically anything that can be done iteratively (with a loop) can be done recursively. There are very few, but not 0, things where it is especially easier one way or the other.