• 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.

Programming |OT| C is better than C++! No, C++ is better than C

Pinewood

Member
I'm not much of a C++ guy, but it's probably one of two things:

1) The visibility of the function in the super class is private and thus not inherited but the sub class.

2) Since the vector name is overridden, the function that accesses that superclass's vector can't be applied to the overwritten vector in the sub class. I'm not sure if inheritance works this way in C++, so it may be a reach.

BTW, why do you have a vector of the same name in the sub class? Why not just use the one that's already there?
Didn't use the vector because it was private. Changed it to protected, ditched the copy and it worked. Thanks.
 

Anustart

Member
How do I get at the damn list here?

Code:
std::vector<std::list<CityCensus> > *data

If that's received by a function? Every damn thing i've tried to do to get at a function of CityCensus results in a "blah blah iterator does not have a member named get_state()"
 
How do I get at the damn list here?

Code:
std::vector<std::list<CityCensus> > *data

If that's received by a function? Every damn thing i've tried to do to get at a function of CityCensus results in a "blah blah iterator does not have a member named get_state()"

I think you would do this.

Code:
(*data)[0].get_census_count()

You have to put parentheses around the dereference because dereferencing has lower precedence than array indexing.
 

Slavik81

Member
How do I get at the damn list here?

Code:
std::vector<std::list<CityCensus> > *data

If that's received by a function? Every damn thing i've tried to do to get at a function of CityCensus results in a "blah blah iterator does not have a member named get_state()"
That's an unusual data structure. You have a pointer to a vector of lists of Censuses.

You'd first have to dereference the pointer, get a list from the vector, get a Census from the list, and then call get_state() on that Census.

Like:
Code:
(*data)[index].front().get_state();

Or to call on every one of them:
Code:
for (auto list : *data)
  for (auto census : list)
    census.get_state();

(I'm using C++11's ranged for loops and auto for brevity, as I'm on my phone. If you're using an earlier C++ standard, you'd need to write those loops slightly differently, but the overall idea is the same.)
 
Okay noob here only started Java really this week, but for the basics i think im catching on quick (for now lol)

now i probably need to clean my formation and naming system, but ill get there.

In anyway, our Java Teacher has not done Java since a long time the Module was pushed on him by surprise so i imagine hes a bit rusty which is fair,
but we had to make a program that will convert Inches to Centimetres and Metres which i though was easy enough,

but when i called him over to look he said my program "was just lazy" and im not sure why, he said something about it but i was kind of in rage mode so i wasnt really listening that moment (he's a nice man though)

in anyway i compare his to mine, and i dont see how mine is lazy, in fact to the no so trained eye it looks akward
let me post a comparrison of Mine and his, and im maybe one of you guys can point me out what about it makes it "lazy"

Mine:
import java.util.Scanner;
class Demo1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);

double inch, centimetre, metre;
double cm_sum=2.54, metre_sum=100;

System.out.println("Please enter Inches to convert? " );
inch = input.nextDouble();
System.out.println(" ");

centimetre = inch*cm_sum;
metre = centimetre/metre_sum;

System.out.println(inch+ " Inches " + centimetre + " Centimetres " + metre + Metres ");


}

}


His:

import java.util.Scanner;
class Demo1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
double inch, centimetre, metre;
double inch_cm=2.54;

System.out.println("Please enter number of inches");
inch=input.nextDouble();
centimetre=inch*2.54;
metre=centimtre/100;
System.out.println(inch+ "inches "+ centimetre + " Centimetres " + metre + " Metre");

}
}

Now im sure someone here has a much easier way but for the sake of the comparrison can someone point me to what im doing and hes doing right?

Thanks

Edit: obviously the code is layed out better on eclipse than copy and pasting it on a board lol
 

Slavik81

Member
Okay noob here only started Java really this week, but for the basics i think im catching on quick (for now lol)

now i probably need to clean my formation and naming system, but ill get there.

In anyway, our Java Teacher has not done Java since a long time the Module was pushed on him by surprise so i imagine hes a bit rusty which is fair,
but we had to make a program that will convert Inches to Centimetres and Metres which i though was easy enough,

but when i called him over to look he said my program "was just lazy" and im not sure why, he said something about it but i was kind of in rage mode so i wasnt really listening that moment (he's a nice man though)

in anyway i compare his to mine, and i dont see how mine is lazy, in fact to the no so trained eye it looks akward
let me post a comparrison of Mine and his, and im maybe one of you guys can point me out what about it makes it "lazy"
They're basically identical so I agree the comment's a little odd.

If I had to guess, he might be refering to your English rather than your Java. As you mention, it still needs to be cleaned up. "Please enter Inches to convert?" is not a question, so it shouldn't end in a question mark. The variables 'cm_sum" and "metre_sum" could use better names, because it's not instantly clear what they're sums of. "cm_per_inch" and "cm_per_metre" would be more descriptive. You are also missing a quotation mark in that last println, but I presume that's just a mistake copying it into this post.

Those are the only real differences between your solution and his, so I presume that's what he was referring to. Perhaps the lesson to take from this is that appearances are important. Trivially easy-to-correct things can actually have quite a significant impact on how your work is perceived. With that being said, I'm not a fan of his prompt text sentence fragment, nor the C89-style variable declarations with them all at the top of the function.
 

Anustart

Member
Ugh. I'm bout done with c++.

I have a vector, looking at a piece of data outside of a loop returns valid data, inside the loop the numbers are way fucking larger. This is in the same function, the data isn't modified so I have no fucking clue what's going on.

Edit: Nevermind, I'm an idiot. I had no break statements in my switch...case so after doing one it was falling through to the next. Headache solved and heart attack stopped!
 

squidyj

Member
got it. The answer to my deduction problem amounted to basically "tell it how many arguments you gave it" it was very simple.

Code:
//concern here is that there might be Many versions?
template<typename... Args>
struct num_elements
{
	static const int value = sizeof...(Args);
};

//separate v from the pack in order to deduce m
//why can't v be an rvalue reference?
//as such the args pack is one less than the number of vectors so we need to increment our returned number of arguments
template<typename... Args, typename T, int m = ++num_elements<Args...>::value, int n>
Matrix<T,m,n> rowMatrix(vector<T, n>& v, Args&&... args)
{
	Matrix<T,m,n> mat;
	_rowMatrix<T, m, n>(0, mat, v, args...);
	return mat;
}

//actually doing the work
template<typename T, int m, int n, typename... Args>
inline void _rowMatrix(int c, Matrix<T, m, n>& mat, vector<T, n>& v, Args&&... vectors)
{
	for(int i = 0; i < n; i++)
		mat.data[c * Matrix<T,m,n>::colOffset + i * Matrix<T,m,n>::rowOffset] = v[i];
	_rowMatrix(++c, mat, vectors...);
}

//terminating condition
template<typename T, int m, int n, typename... Args>
inline void _rowMatrix(int c, Matrix<T, m, n>& mat) {}
 

survivor

Banned
Spending entire day fucking around with ways to deploy a Node.js app while still having capability of writing to filesystem. It's so weird all these cloud services only have temporary filesystems that get deleted every time you restart. Must be some sort of technical design issue where they rather you do your assets loading from a dedicated service like Amazon S3. Oh well, at least getting stats on your server and monitoring it is pretty cool once you have it all figured out.
 
Spending entire day fucking around with ways to deploy a Node.js app while still having capability of writing to filesystem. It's so weird all these cloud services only have temporary filesystems that get deleted every time you restart. Must be some sort of technical design issue where they rather you do your assets loading from a dedicated service like Amazon S3.

This is basically the reason. Cloud hosting or compute resources are heavily abstracted to the point where you have no guarantee at all that your service is running on the same hardware or even in the same data centre from restart to restart. Trying to consistently map those per user would be a logistical nightmare and also hurt availability quite a lot. They need to be able to spin up a host as needed to throw at you and it's much easier if there are no ties to specific h/w.
 

hateradio

The Most Dangerous Yes Man
Edit: obviously the code is layed out better on eclipse than copy and pasting it on a board lol
Use the code tags.

Code:
[plain][code]# code
[/plain][/code]


As far as why the code is lazy, I'm not sure.

In fact, in his he created a variable for CM, but never actually used it.
 

Onemic

Member
Trying to apply CSS to a form and for some reason I can't select any elements within the form itself. There's also a problem with my table that is within the form, as a new line is never made separating the thead row from the tbody row unless I use a <br/> which I shouldn't need to use.

The width of the form is also oddly larger than the width of the body which is set to 1024px. The only way I was able to fix this was by setting the width to both the body and the form instead of just the body, event though the form is within the body element. Anyone know what's going on?

http://codepen.io/anon/pen/vEOvEW
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Trying to apply CSS to a form and for some reason I can't select any elements within the form itself. There's also a problem with my table that is within the form, as a new line is never made separating the thead row from the tbody row unless I use a <br/> which I shouldn't need to use.

The width of the form is also oddly larger than the width of the body which is set to 1024px. The only way I was able to fix this was by setting the width to both the body and the form instead of just the body, event though the form is within the body element. Anyone know what's going on?

http://codepen.io/anon/pen/vEOvEW

Is there a reason you are using px units instead of percentages?
 

Slo

Member
Hey guys, so Im fresh out of college, and I have an interview setup next week for a position as an automation tester.

Can anyone give me any details on it? Does anyone here have experience in that position?

I did a 3 year diploma in Software Development, which covered c#, java, Oracle 11g, Sql Server 2012, html and php.

I have no real world experience in coding but I did do very well in my studies. I haven't designed test cases before.

Apologies if this is a bit off topic.

What you need to do is do some research on test case design. Be able to design a good test case. Google test case template and get to know the general concept. Especially with automated testing, you need to be able to define the component being tested, the conditions it's being tested under, the inputs, and the expected outputs.

You need to be able to write a good defect. Use your Google machine to figure out how to write a defect in a manner in a way that a programmer can consume it. Hint: a well written defect is very very similar to a well written test case.

Familiarize yourself and be able to describe the difference between Unit testing, Functional testing, Performance testing, system testing, etc.

Become aware of common testing tools such as JUnit or Selenium.

Know the basics of Ant, Maven, Windows bat files, and unix shell scripts.

Be a "destructive" person by nature. You better like to break things more than you like to create things if you're in QA.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Just what I'm used to using as my professor pretty much only uses it.

Ok. Percentages will fix your overall width issues. just use 90% with 1% margins or something instead.

Form wise, a quick and dirty solution could be to just throw an id into the forms you want to modify. id="form-i-want"

Then in the CSS just refer to that id.

#form-i-want {
stuff: things
}
 

gotoadgo

Member
Who has some good resources for learning asp .net? Starting a new position in 5 weeks and would like to get some learning in before I start.
 

Onemic

Member
Ok. Percentages will fix your overall width issues. just use 90% with 1% margins or something instead.

Form wise, a quick and dirty solution could be to just throw an id into the forms you want to modify. id="form-i-want"

Then in the CSS just refer to that id.

#form-i-want {
stuff: things
}

The percentages fixed the first part, thanks.

The second part though, mainpulating the forms with CSS doesn't work. My thead elements still act strange and dont make a new line after the ending tag unless I add a <br/> and trying to use CSS either through accessing the element directly or with an id/class still doesnt do anything.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
The percentages fixed the first part, thanks.

The second part though, mainpulating the forms with CSS doesn't work. My thead elements still act strange and dont make a new line after the ending tag unless I add a <br/> and trying to use CSS either through accessing the element directly or with an id/class still doesnt do anything.

Try something besides your table setup. You are using fieldsets within forms currently, so expand on that and utilize them for the entire layout. I think that will give you more control over your styling. Use <p> tags instead of </br>. You can add id's classes to <p> tags you need to style as well.

Obviously there are a lot of other ways to solve this problem, but this is one that deviates only slightly from your original code.

Code:
<form>
  <fieldset>
    <legend>Basic Information</legend>
    <p>First Name: <input type="text" name="firstName"> * </p>
    <p>Last Name: <input type="text" name="lastName"> * </p>
    <p>Student ID: <input type="text" name="studentID"> * </p>
    <p>Learn ID: <input type="text" name="learnID"> * </p>
    <!-- etc etc etc -->
    </fieldset>
</form>
 

Onemic

Member
Try something besides your table setup. You are using fieldsets within forms currently, so expand on that and utilize them for the entire layout. I think that will give you more control over your styling. Use <p> tags instead of </br>. You can add id's to <p> tags you need to style as well.

Obviously there are a lot of other ways to solve this problem, but this is one that deviates only slightly from your original code.

Code:
<form>
  <fieldset>
    <legend>Basic Information</legend>
    <p>First Name: <input type="text" name="firstName"> * </p>
    <p>Last Name: <input type="text" name="lastName"> * </p>
    <p>Student ID: <input type="text" name="studentID"> * </p>
    <p>Learn ID: <input type="text" name="learnID"> * </p>
    <!-- etc etc etc -->
    </fieldset>
</form>

Thanks, that solved it.

One last question. Do you know how you would be able to center and justify the text/fields within the table? I only seem to be able to center the elements, but not justify them.
 

D4Danger

Unconfirmed Member
The percentages fixed the first part, thanks.

The second part though, mainpulating the forms with CSS doesn't work. My thead elements still act strange and dont make a new line after the ending tag unless I add a <br/> and trying to use CSS either through accessing the element directly or with an id/class still doesnt do anything.

You have everything in a single table row

<tr> creates a row
<td> creates a cell

what you're trying to do should look more like

Code:
<table>
  <tr>
    <td>Label 1</td>
    <td><input type="text" /> *</td>
  </tr>
  <tr>
    <td>Label 2</td>
    <td><input type="text" /> *</td>
  </tr>
</table>

etc

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td

You could then style the <tr> or <td> or use some classes or whatever
 

Onemic

Member
You have everything in a single table row

<tr> creates a row
<td> creates a cell

what you're trying to do should look more like

Code:
<table>
  <tr>
    <td>Label 1</td>
    <td><input type="text" /> *</td>
  </tr>
  <tr>
    <td>Label 2</td>
    <td><input type="text" /> *</td>
  </tr>
</table>

etc

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td

You could then style the <tr> or <td> or use some classes or whatever

Yup, already did that, my new problem is the post above :p
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Thanks, that solved it.

One last question. Do you know how you would be able to center and justify the text/fields within the table? I only seem to be able to center the elements, but not justify them.

Which table are you referring to?

Those things can be accomplished through CSS by just adding a class to whatever elements you need to modify and then writing in the parameters into the CSS.

To justify you would use the { text-justify: argument } property. Documentation
 

Onemic

Member
Which table are you referring to?

Those things can be accomplished through CSS by just adding a class to whatever elements you need to modify and then writing in the parameters into the CSS.

To justify you would use the { text-justify: argument } property. Documentation

All the tables. I want it to be center justified like this:

sample-registration-form-validation.gif
Except that all the fields have the same width.

Like I said before, I can center the elements, but justifying them does nothing.

http://codepen.io/anon/pen/vEOvEW
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
All the tables. I want it to be center justified like this:

Except that all the fields have the same width.

Like I said before, I can center the elements, but justifying them does nothing.

http://codepen.io/anon/pen/vEOvEW

I'm starting to feel like this is a homework assignment, and I don't want to give you all of the answers.

Here is a nice website with some good information about form layouts though. See if that helps, and do some research into the layout properties available with CSS.
 
As i have stated im still only new, my second week of learning java,

but im trying to create a Flowchart in Java, yeah i understand is best to draw it out first using different shapes and such.
Im having troubling implementing it to Java, im trying to create it using nested ifs, but having trouble with the layout, dont really know the terminology yet to explain correctly what im doing lol,

i thought using "switch" would be better but it wont accept string, or at least i don't know how to yet

so im wondering if someone could give me a very simple 2-3 step flowchart in Java using string if possible.

sorry for how im writing this i don't mean to insult you with my stupidity, im really loving it, haven't had this much fun since awhile.
 

poweld

Member
As i have staed im still only new, my second week of learning java,

but im trying to create a Flowchart in Java, yeah i understand is best to draw it out first using different shapes and such

but im having troubling implementing it to Java, im trying to create it using nested ifs, but having trouble with the layout, dont really know the terminology yet to explain correctly what im doing lol,

i thought using "switch" would be better but it wont accept string, or at least i don't know how to yet

so im wondering if someone could give me a very simple 2-3 step flowchart in Java using string if possible.

sorry for how im writing this i don't mean to insult you with my stupidity, im really loving it, haven't had this much fun since awhile.

https://docs.oracle.com/javase/7/docs/technotes/guides/language/strings-switch.html
 
From one thing to another, can anybody explain to me why this isn't working

i copied the code from the net got no errors, but when i try to run it this happens

Screen_shot_2014_11_28_at_21_44_33.png


i'm running Eclipse IDE with Java with 1.6.0 JDK on Imac 10.06.8 if that helps
 

arit

Member
From one thing to another, can anybody explain to me why this isn't working

i copied the code from the net got no errors, but when i try to run it this happens

Screen_shot_2014_11_28_at_21_44_33.png


i'm running Eclipse IDE with Java with 1.6.0 JDK on Imac 10.06.8 if that helps

Strings in switch statements have only been supported since Java 7. So either update to a current JDK > 1.6.x or don't try to use them.
 
Strings in switch statements have only been supported since Java 7. So either update to a current JDK > 1.6.x or don't try to use them.

Yeah just researching there Java 7 is not supported for my OS, Java 6 being highest damn!

would you suggest i use nested ifs for now? or just go with using int over string?
Thank you
 

OceanBlue

Member
Yeah just researching there Java 7 is not supported for my OS, Java 6 being highest damn!

would you suggest i use nested ifs for now? or just go with using int over string?
Thank you

You can do if/else if/else and string.equals("something"). Kinda like this
Code:
if (command.equals("something")) {
  do something
} 
else if (command.equals("something else")) {
  do something else
}
Edit: Err if that's what you meant by nested ifs, my bad lol.
 
You can do if/else if/else and string.equals("something"). Kinda like this
Code:
if (command.equals("something")) {
  do something
} 
else if (command.equals("something else")) {
  do something else
}
Edit: Err if that's what you meant by nested ifs, my bad lol.

Yeah thats what i meant, but i tried doing it but im having trouble with that.....
before i explain that, everything went from bad to worst, i was getting a few preferences errors but eventually cleaned them up deleted all my files in Eclipse, shut Eclipse down, tried to open it again but now Eclipse wont open
WTF?

i tred deleted and reinstalling eclipse, and re updating my Java,
still wont open.

its really frustrating, anyone have this problem?

edit: did
java - version
in terminal and i got return
could not create the java virtual machine
which is very weird unless i somehow i accidentally deleted the VM package thats my only guess
 
I did both i had Wine and eclipse open at the same time, when i closed Wine, and restarted my computer

Eclipse wouldn't load, i think Wine did something to fuck with the Pathways because -vm and -bash are not commands anymore, which is weird as fuck?
 

Slo

Member
I did both i had Wine and eclipse open at the same time, when i closed Wine, and restarted my computer

Eclipse wouldn't load, i think Wine did something to fuck with the Pathways because -vm and -bash are not commands anymore, which is weird as fuck?

It does sound like your path is messed up. Sorry, I'm not a Mac guy so I won't know how to go about fixing it.
 
It does sound like your path is messed up. Sorry, I'm not a Mac guy so I won't know how to go about fixing it.

Okay thanks in anyway i don't know if i should make a separate thread about this as this seems to be beyond Java, and people on here seem to have a good knowledge on this stuff.

alternatively i could go StackFlow but my last question there i got the head blown of me because ii didn't match there preferred technical terminology haha
 

Massa

Member
I did both i had Wine and eclipse open at the same time, when i closed Wine, and restarted my computer

Eclipse wouldn't load, i think Wine did something to fuck with the Pathways because -vm and -bash are not commands anymore, which is weird as fuck?

Try running java -version under a guest user account.
 
when i try to run eclipse i get this
/Applications/Eclipse.app/Contents/MacOS/eclipse ; exit;
Luke:~ lukekearns$ /Applications/Eclipse.app/Contents/MacOS/eclipse ; exit;
Bus error
logout

[Process completed]
/QUOTE]

Notice the Bus error
 

upandaway

Member
I'm giving up, my head hurts. I'm using C. Can someone please help?

I need to take a double and print it as: {the sum of the integer part's digits}.{the sum of the decimal part's digits}
For example, 123.22 -> 6.4 or 99.99 -> 18.18

I don't know the length of the decimal part so I keep hitting the double precision issue whenever I try to do anything with it. My instinct was:

Code:
n -= (int) n                   //reset n to its decimal part
while (n != 0)
    n *= 10                    //advance one digit to the right
    sum += (int) n % 10        //add that digit to sum
    n -= (int) n               //reset n to its decimal part again

It ends up being an infinite loop because instead of hitting 0, n stays at .99999 or something. Everything on the internet I found can only solve the issue by knowing how many decimal digits there are.
I'm only interested in the sum to I don't care how many 0's there are on either side.


I'm starting to think C would not be so bad if they would only let me use it. Everything is "must use scanf" this or "don't use arrays" that or whatever, it's the worst. This wouldn't be a problem with a pointer.
Any advice welcome
 
You could try transforming the float in a char array.

Code:
	float n = 10.734;
	char array[20];
	sprintf(array, "%f", n);

The only thing you have to be careful is the char array be big enough to hold the float.

Then you would only need to iterate though the char values and convert them to int
 

upandaway

Member
You could try transforming the float in a char array.

Code:
	float n = 10.734;
	char array[20];
	sprintf(array, "%f", n);

The only thing you have to be careful is the char array be big enough to hold the float.

Then you would only need to iterate though the char values and convert them to int

Oh sorry I forgot to write clearly, only mentioned it at the end of the post, but yeah we can't use arrays or strings or pointers or any sort of library aside from stdio. I really wish we could
 
Hello, I need some help choosing a topic for a programming assignment in Java.

I need to pick something that is related to Monte Carlo simulation or is heavily reliant on mathematics (can prove the results by code and theoretically) and I feel like I've hit a brick wall.


Thanks!
 
Oh sorry I forgot to write clearly, only mentioned it at the end of the post, but yeah we can't use arrays or strings or pointers or any sort of library aside from stdio. I really wish we could

Rouding errors. I remember having problems before, here is something I cooked up

Code:
	int sum = 0;
	double n = 10.13009099;      //it works
	//double n = 10.13009099009; //uncomment to check rounding errors
	
	n -= (int) n;                //reset n to its decimal part
	printf("%lf \n", n);
	n *= 10;
	while (n>10e-6) {          //n!=0 is not a condition you should be checking due to rounding error depending on the double, you should check for a number close to 0
		printf("N before: %lf \n", n);
		if (n >= 1.0) {                            // ignore if n is less than one
			sum += (int) n % 10;       //add that digit to sum
			// sum += (int) (n + 10e-6) % 10;  //add that digit to sum, sums 10e-6 to n to fix rounding error
			printf("Sum: %d \n", sum);
			//n -= (int) (n + 10e-6);             //reset n to its decimal part again, sums 10e-6 to n to fix rounding error
			n -= (int) n;                     //reset n to its decimal part again, has rounding error
		}           
		n *= 10; 		                  //advance one digit to the right
	}
	printf("%d \n", sum);

First I recommend running the program as it is to see the rouding errors/

Then uncomment the two lines in the loop that fix rouding errors, commenting the other two ones.

Finally, uncomment the n declaration to see that the rouding erros come back due to having a bigger decimal value.

I hope that helps you.
 

upandaway

Member
Thanks a lot colossal-man, I'll have to look at it carefully tomorrow since my project is on the other computer. I do remember seeing rounding errors when I printed the whole process with no clue how to solve it. If I get what you're saying, there's no way to solve it without knowing the amount of precision needed?
 
Thanks a lot colossal-man, I'll have to look at it carefully tomorrow since my project is on the other computer. I do remember seeing rounding errors when I printed the whole process with no clue how to solve it. If I get what you're saying, there's no way to solve it without knowing the amount of precision needed?

Thats pretty much the gist of it. You could stipulate a max precision for the double.

But then in your assignement, it must be any double then. One thing you should remember, decimal numbers in computers are for the most part not accurately represented.
 

tokkun

Member
I'm giving up, my head hurts. I'm using C. Can someone please help?

I need to take a double and print it as: {the sum of the integer part's digits}.{the sum of the decimal part's digits}
For example, 123.22 -> 6.4 or 99.99 -> 18.18

I don't know the length of the decimal part so I keep hitting the double precision issue whenever I try to do anything with it. My instinct was:

Code:
n -= (int) n                   //reset n to its decimal part
while (n != 0)
    n *= 10                    //advance one digit to the right
    sum += (int) n % 10        //add that digit to sum
    n -= (int) n               //reset n to its decimal part again

It ends up being an infinite loop because instead of hitting 0, n stays at .99999 or something. Everything on the internet I found can only solve the issue by knowing how many decimal digits there are.
I'm only interested in the sum to I don't care how many 0's there are on either side.


I'm starting to think C would not be so bad if they would only let me use it. Everything is "must use scanf" this or "don't use arrays" that or whatever, it's the worst. This wouldn't be a problem with a pointer.
Any advice welcome

Double precision floating point is a binary format. I do not recommend trying to process it using decimal arithmetic. It will be a lot easier to avoid rounding errors if you work with base-2 arithmetic.

I would suggest denormalizing the number by repeatedly multiplying or dividing it by 2 until you have converted the mantissa to an unsigned 64-bit integer and have the exponent for the denormalized number.

Alternatively, you could do this by bit casting the double to a long int and extracting the bit fields, but it sounds like you are saying you are not allowed to use pointers.

From that point, you should be able to separate the the mantissa into the integral and fractional parts using bit operations. At that point, it is safe to do the conversion with base-10 arithmetic.

There are a couple things to be careful about with this approach. Don't forget about the implicit leading one. Make sure to take the absolute value of the input number. Figure out whether you are expected to handle special cases, like zero, subnormals, NaN, or infinity.

Let me also add that doing a C-style cast of double to int
Code:
(int) my_double
is not safe, because it is possible for a double to hold values that are larger than the maximum int value.
 
Hello, I need some help choosing a topic for a programming assignment in Java.

I need to pick something that is related to Monte Carlo simulation or is heavily reliant on mathematics (can prove the results by code and theoretically) and I feel like I've hit a brick wall.


Thanks!

What's the scale of the problem supposed to be? You could do Monte Carlo integration which does not seem overly difficult to implement (in its simplest form). There's also a lot of ways in which you could refine the process.
 
Top Bottom