• 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

I had the same experience. Started using Scala around 2 years ago, 5 years into my professional experience. Everything felt like it was turned on its head. The good news is that after I got more comfortable with FP, it was a euphoric experience. Adjusting logic, multithreading, working with complicated/deeply nested structures all became much easier to write and read.

What's a good project to start, I've been trying to get into scala foreve
 

Massa

Member
I'm actually less interested in the game aspects and mainly just playing around with graphics rendering at lower levels - maybe even get to doing some low-level rendering using 3D math, that sort of thing (think like orginial Wolfenstein level pseduo-3D kind of stuff). So, I'm not even really terribly interested in hardware accelerated 3D at this point (or even 3D at all yet, I'm perfectly fine just doing 2D as simply doing graphics period is novel enough for me, haha!).

There isn't much difference between 2D and 3D if you want to learn on that level. 2D programs will only be slightly simpler to start with, but you'll still need to learn the same concepts.

Whether you go with WebGL or modern shader-based OpenGL doesn't matter, what you're interested in is using the OpenGL Shading Language (GLSL).

I've used Angel's "Interactive Computer Graphics: A Top-Down Approach" and it's pretty good, check that out if you can find it.
 

Makai

Member
I had the same experience. Started using Scala around 2 years ago, 5 years into my professional experience. Everything felt like it was turned on its head. The good news is that after I got more comfortable with FP, it was a euphoric experience. Adjusting logic, multithreading, working with complicated/deeply nested structures all became much easier to write and read.
Is that your primary language now? I imagine job prospects for any functional language are low. I'm a C# programmer so F# will be my language of choice soon, but the one guy at work who knew F# got in trouble for using it.
 
Code:
#include <iostream>
using namespace std;

int main()
{
    int i, n;
    
    cout << "Enter an n value";
    cin >> n;
    i=1;
    
    
    while (i<=n){
          cout << i << " ";
          [B]i=i+1[/B];
}
      
    system("pause");
    return 0;
}

whys it when i try i=i++ instead of i=i+1 the program print 1's forever?

arent they supposed to run the same thing?
 

mercviper

Member
Code:
#include <iostream>
using namespace std;

int main()
{
    int i, n;
    
    cout << "Enter an n value";
    cin >> n;
    i=1;
    
    
    while (i<=n){
          cout << i << " ";
          [B]i=i+1[/B];
}
      
    system("pause");
    return 0;
}

whys it when i try i=i++ instead of i=i+1 the program print 1's forever?

arent they supposed to run the same thing?

i=i++; isn't a thing and I guess the compiler isn't catching it. The statement for that is only "i++;"
 
Pretty sure that i=i++ _is_ a thing, just not a particularly useful thing.

Semantically it requests the compiler to write code to increment i, then assign the value of that expression to i. Since the value of i++ is the value of i prior to the increment, i ends up with its original value.
 

mercviper

Member
Pretty sure that i=i++ _is_ a thing, just not a particularly useful thing.

Semantically it requests the compiler to write code to increment i, then assign the value of that expression to i. Since the value of i++ is the value of i prior to the increment, i ends up with its original value.

Oh, yeah that could be it. I was wondering why it wouldn't use the new value of i, but it would happen after the original value is sent to cache and before i is assigned it's new value. "i=++i;" should work fine then since it increments before being used.
 

poweld

Member
Is that your primary language now?
No, at this point I don't think I have a primary language, for better or worse. If I could choose I would use it more often, or another language with a strong FP offering. Currently I write mostly Java.

I imagine job prospects for any functional language are low.

Quite the opposite. Since my time working in Scala, about half of the headhunters reaching out are asking me to join some Scala shop. Not sure what to attribute that to, exactly.

I'm a C# programmer so F# will be my language of choice soon, but the one guy at work who knew F# got in trouble for using it.
He... got in trouble?
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Quite the opposite. Since my time working in Scala, about half of the headhunters reaching out are asking me to join some Scala shop. Not sure what to attribute that to, exactly.

I would guess a vastly smaller talent pool. It might not top any lists for most profitable/popular languages, but there is a still a small demand for it and as long as it's not being met, being in that niche means you become a valuable asset.
 

Chris R

Member
He wrote the core of an app in F# and the VP of engineering made him rewrite it in C#. The rest of us only know C#, so we wouldn't be able to maintain it. He wasn't reprimanded or anything.

Well, I'd ask the same thing.

I write my personal projects in C#, but anything that ends up in a repo at work is in VB.Net so the other developers can maintain it in the future if need be. I'd still never commit something in C# since I know it would be an issue because it's different, even if the difference is almost purely visual.
 

SOLDIER

Member
Need help with my latest Python assignment: Speeding Violation Calculator

Design a program that calculates and displays the number of miles per hour over the speed limit that a speeding driver was doing. The program should ask for the speed limit and the driver's speed. Validate the input as follows:

-The speed limit should be at least 20, but not greater than 70.

-The driver's speed should be at least the value entered for the speed limit (otherwise the driver was not speeding).

Once correct data has been entered, the program should calculate and display the number of miles per hour over the speed limit that the driver was doing.

Examples would be very helpful.
 
You take the speed limit as an input, and the driver's speed.

then you compare their speed to the speed limit like:

if (drivspeed > limit){
ayy= drivspeed - limit
print("you were driving",ayy,"over the limit.")
}

that's just pseudocode btw, do it in python syntax.

I have to make a client/server on c with tcp and udp sockets and it's due on Wednesday. SMH i haven't even started, shit intimidated me so much I just kept putting it off. :(

does anybody know of an examples of a program running both connections concurrently? I understand fork and select need to be used. I've seen examples of both individually but none together.
 

mooncakes

Member
Going to need help on this assignment for python 2.7

It keeps looping and when i put numbers of dice roll is 0, is an error



Calculates the number of times the sum of the randomly rolled dice equals each possible value from 2 to 12

Repeatedly asks the user for the number of times to roll the dice, quitting only when the user-entered number is less than 1. Hint: Use a while loop that will execute as long as num_rolls is greater than 1.

import random

num_rolls = int(input('Enter number of rolls:\n'))

while num_rolls <= 1:
num_sixes =0
num_sevens =0

for i in range(1,num_rolls+1):
die1 = random.randint(1,6)
die2 = random.randint(1,6)
roll_total = die1 + die2

#Count number of sixes and sevens

if roll_total == 6: num_sixes += 1
elif roll_total == 7: num_sevens += 1

print('Roll %d is %d (%d + %d)' % (i, roll_total, die1, die2))

print('\nDice roll statistics:')
print('6s:', num_sixes)
print('7s:', num_sevens)

num_rolls = int(input('Enter number of rolls:\n'))
 

poweld

Member
Going to need help on this assignment for python 2.7

It keeps looping and when i put numbers of dice roll is 0, is an error

It's going to be very difficult to help you since the code you posted isn't formatted correctly. Indentation in python matters. Consider posting to pastebin or something and double check your formatting.

Also, post the error.

edit: Right off the top, I imagine you wanted to use >= (greater than or equal) when checking the value of num_rolls
 

endre

Member
I need some guidance with a C# app I am writing to make my life at work easier. I figured this is a good opportunity to learn OOP as well.

I want to extract entities from a dxf file, such as lines, points, circles and arcs. It is an ASCII version that can be read with a text editor. Here is an example, how are entities stored:

Code:
ENTITIES
  0
LINE
  5
C2
330
1F
100
AcDbEntity
  8
0
100
AcDbLine
 10
50.0
 20
50.0
 30
0.0
 11
50.0
 21
60.0
 31
0.0
  0
LINE
  5
C3
330
1F
100
AcDbEntity
  8
0
100
AcDbLine
 10
50.0
 20
60.0
 30
0.0
 11
90.0
 21
60.0
 31
0.0
  0
LINE
  5
C4
330
1F
100
AcDbEntity
  8
0
100

From here I would extract the position of an entity. My question is, how can I store entities as objects?

Lets say I make a class called Line, which can hold data about coordinates and has some relevant methods. How can I instantiate objects during runtime since I do not know how many line entities are there until I evaluate a file. In other words, I would like to create instances during runtime called Line1, Line2 etc.

Additionally, how can I check how many instances of a class have been created? Should I make a static class variable to count instances which is then incremented in the constructor?

I'd appreciate any suggestions or links to some tutorials. Thanks.
 
I need some guidance with a C# app I am writing to make my life at work easier. I figured this is a good opportunity to learn OOP as well.

I want to extract entities from a dxf file, such as lines, points, circles and arcs. It is an ASCII version that can be read with a text editor. Here is an example, how are entities stored:

Code:

From here I would extract the position of an entity. My question is, how can I store entities as objects?

Lets say I make a class called Line, which can hold data about coordinates and has some relevant methods. How can I instantiate objects during runtime since I do not know how many line entities are there until I evaluate a file. In other words, I would like to create instances during runtime called Line1, Line2 etc.

Additionally, how can I check how many instances of a class have been created? Should I make a static class variable to count instances which is then incremented in the constructor?

I'd appreciate any suggestions or links to some tutorials. Thanks.

It sounds like you just want to put the line objects in a list. You'd probably want a DxfParser class that looks something like this
Code:
class DxfParser {
    public List<Entity> ParseFile(string path) {
        var entites = new List<Entity>();

        // Parse the file, adding entities to the list

        return entities;
    }
}
I've replaced Line by Entity in my example since you might want to parse more than just lines (Entity could be an abstract class or an interface).
 

endre

Member
It sounds like you just want to put the line objects in a list. You'd probably want a DxfParser class that looks something like this
Code:
class DxfParser {
    public List<Entity> ParseFile(string path) {
        var entites = new List<Entity>();

        // Parse the file, adding entities to the list

        return entities;
    }
}
I've replaced Line by Entity in my example since you might want to parse more than just lines (Entity could be an abstract class or an interface).

I already wrote something similar to this. I am extracting the section of the file containing information about entities to a list. Now I want to separate each entity to a unique collection or variable. First I thought to store the lines into an array that would look like this:

Code:
int[][,,,] Lines=new int int[line number][X1,Y1,X2,Y2]
X1,Y1 - line start coordinates
X2,Y2 - line end coordinates


But now I would like to take a different approach. I would like to make each entity an object and to create these objects at runtime.
 
I feel so stupid, I do pretty well in programming class for the first 2 chapters then I just hit a brick wall and everything becomes so difficult for me:( Same thing happened in Java and now C++, I'm falling behind already and another few classes and I won't be able to catch up.
 
Long time, no post.

For a program installer, would they do anything outside of writing to the file system and registry on Windows?

They can do just about anything. I wrote an installer once that configured a networked data store targeting up to five possible database vendors and performed a full in-situ migration from three previous product levels if one was detected. There's no end of what kind of madness you can stuff into an installer, you just have to weigh whether or not the automation is going to be worthwhile to your intended userbase.
 
Problem 1

Write a complete C++ program that does the following.
1. It asks the user to enter an integer between 100 and 9999.
2. If the entered number is out of range, the program forces the user to enter more numbers until one in the correct
range is given.
3. Then the program prints the digits in the number (in reverse) on separate lines.

Here is an example of how the program should work:

Enter an integer between 100 and 9999: 8976
6
7
9
8

Answer:

Code:
#include <iostream>
using namespace std;
int main() {
int n;
cout << "Enter an integer between 100 and 9999: ";
cin >> n;
while (n < 100 || n > 9999) {
cout << "Out of range. Try again: ";
cin >> n;
}
while (n > 0) {
cout << n % 10 << endl;
n = n / 10;
}
return 0;
}

this part in particular me has me scratching my head:
Code:
while (n > 0) {
cout << n % 10 << endl;
n = n / 10;
}
return 0;
}

im trying to figure out how the last bit works.. I can memorize it but it isn't making sense to how it makes a number get spit out backwards on separate lines.

if i set n=25, 25%10 = 5 so i can see that's where the 5 on the first line comes from

but then with n/10, we get 25/10 = 2 but i don't see how or why it gets printed on the next line
 

Koren

Member
but then with n/10, we get 25/10 = 2 but i don't see how or why it gets printed on the next line
The computation (division) is done on integers...

So 25/10 gives 2.5, which is not an integer, so the result is the integer part of it, which is 2

8976/10 = 897 and 8976%10 gives 6
897/10 = 89 and 897%10 gives 7
89/10 = 8 and 89%10 gives 9
8/10 = 0 and 8%10 gives 8
 
The computation (division) is done on integers...

So 25/10 gives 2.5, which is not an integer, so the result is the integer part of it, which is 2

8976/10 = 897 and 8976%10 gives 6
897/10 = 89 and 897%10 gives 7
89/10 = 8 and 89%10 gives 9
8/10 = 0 and 8%10 gives 8

So what I think I'm understanding is that the program starts at 25 % 10 and spits out 5 and ends the line.

Then it takes 25 and runs it through n = n/10; to get 25/10=2.

And finally it takes that 2 and runs it through n = n%10; to give 2%10=2.
 

Koren

Member
So what I think I'm understanding is that the program starts at 25 % 10 and spits out 5 and ends the line.

Then it takes 25 and runs it through n = n/10; to get 25/10=2.

And finally it takes that 2 and runs it through n = n%10; to give 2%10=2.
That's correct...

Then, 2/10 equals 0, so you exit the while (n>0) loop.
 

Dereck

Member
There is an if statement in java, and the if statement has two else ifs and another if.

If the first if statement is true, does that mean that Java stops reading anything else below it in the same statement, or does it keep going? Example

Code:
int y = 99
int x = 30
int z = 20

if (y > 1) {
    System.out.println("OK");
    if (x > 1) { System.out.println("Nah"); }
    } else if ( z > 1) {
    System.out.println("Whoa");
    } else if (y > 1) {
    System.out.println("Yeah");
      if (x > 1) ( System.out.println("King"); }
      System.out.println("X");
    }
  }
}
 

Chris R

Member
Firstly, your code won't run in it's present state. Format it in a consistent manner to help prevent those errors in the future. It also helps by making the code more readable.

Code:
if (y > 1) {
    System.out.println("OK");
    if (x > 1) { 
        System.out.println("Nah");
    }
} else if (z > 1) {
    System.out.println("Whoa");
} else if (y > 1) {
    System.out.println("Yeah");
    if (x > 1) {
        System.out.println("King");
    }
    System.out.println("X");
}

This code would print out

OK
Nah

Because (y > 1) is true and (x > 1) is true as well. The secondary else if (z > 1) and another (y > 1) are never run with the current variable values.
 

w3bba

Member
There is an if statement in java, and the if statement has two else ifs and another if.

If the first if statement is true, does that mean that Java stops reading anything else below it in the same statement, or does it keep going? Example

I dont quite get what you mean by statement below.

Generally speaking:
- If the statement is true, everything in the block for thet statement (in curly braces) gets executed.
- All other else-if and else statements will be ignored.
- The code continues after the if-else block after the appropriate block was executed

for your example the output would be:

OK
Nah
X

PS: Have you copied too many closing braces there? the last 3 are orphaned
 
Problem I got to do, but I slightly confused and I am wondering if I am on the right track.

I am using VS express

So far I got

#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;
int main()
{
ifstream inFile;
ofstream outFile;

inFile.open("inData.txt");
outFile.open("outData.txt");

cout << " Rectangle";
cout << endl;
cout << " Length = 10.20";
cout << endl;
cout << " width = 5.35 ";
cout << endl;
cout << " area = 54.57";
cout << endl;
cout << "parameter = 31.10" << endl;
}

I need to
A. Write a statement that includes the header files fstream, string, and iomanip in this program.
B. Write statements that declare inFile to be an ifstream and outFile to be an ofstream variable.
C. The program will read data from the file inData.txt and write output to the file outData.txt. Write statements to open both of these files, associate inFile with inData.txt, and outFile with outData.txt.
D. Suppose that the file inData.txt contains the following data:
10.20 5.35
15.6
Randy Gill 31
18500 3.5
A
The numbers in the first line represent the length and width of a rectangle.The number in the second line represent a radius of a circle.The third line is a first name, last name, and age.The fourth line is a savings account balance, as well as an interest rate.The fifth line contains an Uppercase letter between A and Y(inclusive). Write statements so that after the program executes, the contents of the file outData.txt are shown below. If necessary, declare additional variables. Your statements should be general enough so that if the content of the input file changes and the program is run again (without editing and recompiling), it outputs the appropriate results

Rectangle:
Length = 10.20, width = 5.35 , area = 54.57, parameter = 31.10

circle:
Radius = 15.60, area = 764.54, circumference = 98.02

Name: Randy Gill age: 31
Beginning balance = $18500.00, interest rate = 3.50

Balance at the end of the month $18553.96

The character that comes after A in the ASCII set is B.
 

SOLDIER

Member
This is what I have so far with Python:

Code:
def ask_limit():
    limit = float(input ("Enter the speed limit: "))
        
    return limit
def ask_speed():
    speed = float(input ("Enter the driver's speed: "))
    return speed
def over_limit(speed, limit):
    if speed > 70:
        over_limit = (speed - limit)
        print ("You are over the speed limit by: "), over_limit
    elif speed <= limit:
        print ("You are maintaining the speed limit.")
    else:
        over_limit = ((speed - limit) * 5 + 50)
        print ("your fine is "), fine
    
            
def main():
    limit = ask_limit()
    speed = ask_speed()
    over_limit = (speed, limit)
main()

It will ask me to put in the speed limit and the driver's speed, but it doesn't display anything after that.

I need it to say how many mph over the speed limit the driver would be going. For example, if it went 75 in a 70 mph zone, it should say "You are 5 miles over the speed limit!". Similarly, it should also say when I'm maintaining the speed limit if I enter a number that doesn't exceed it.
 

Haly

One day I realized that sadness is just another word for not enough coffee.
Well you're comparing "speed > 70" rather than "speed > limit", I don't know if that's affecting your tests.
 
This is what I have so far with Python:

Code:
def ask_limit():
    limit = float(input ("Enter the speed limit: "))
        
    return limit
def ask_speed():
    speed = float(input ("Enter the driver's speed: "))
    return speed
def over_limit(speed, limit):
    if speed > 70:
        over_limit = (speed - limit)
        print ("You are over the speed limit by: "), over_limit
    elif speed <= limit:
        print ("You are maintaining the speed limit.")
    else:
        over_limit = ((speed - limit) * 5 + 50)
        print ("your fine is "), fine
    
            
def main():
    limit = ask_limit()
    speed = ask_speed()
    over_limit = (speed, limit)
main()

It will ask me to put in the speed limit and the driver's speed, but it doesn't display anything after that.

I need it to say how many mph over the speed limit the driver would be going. For example, if it went 75 in a 70 mph zone, it should say "You are 5 miles over the speed limit!". Similarly, it should also say when I'm maintaining the speed limit if I enter a number that doesn't exceed it.

You can invoke over_limit without the need for a variable. So rather than writing:
Code:
over_limit = (speed,limit)
You can just call over_limit directly, like so:
Code:
over_limit(speed,limit)
Over_limit doesn't have a return type, so you can just call on it directly by passing it two values.

Additionally, you can just append the value of over_limit in your print statement, to a string. So rather than
Code:
print ("You are over the speed limit by: "), over_limit
, You can just write
Code:
print("You are over the speed limit by: " + str(over_limit))

Hope that helps!
 

SOLDIER

Member
Made the changes, but it still won't tell me how much I'm over the limit (or if I'm maintaining it):

Code:
def ask_limit():
    limit = float(input ("Enter the speed limit: "))
        
    return limit
def ask_speed():
    speed = float(input ("Enter the driver's speed: "))
    return speed
def over_limit(speed, limit):
    if speed > limit:
        over_limit(speed - limit)
        print ("You are over the speed limit by: " + str(over_limit))
    elif speed <= limit:
        print ("You are maintaining the speed limit.")
    
def main():
    limit = ask_limit()
    speed = ask_speed()
    over_limit = (speed, limit)
main()
 
You can just call it. No need to write return, just call it within main, and the method over_limit(speed,limit) will execute.

For your other two functions ask limit() & ask_speed(), the final line of each method is returning something (limit and speed respectively).

over_limit(speed,limit) just executes the method when you call it directly. So all you need to write it is :
Code:
def main():
    limit = ask_limit()
    speed = ask_speed()
    over_limit(speed, limit)
main()
 
I'm actually less interested in the game aspects and mainly just playing around with graphics rendering at lower levels - maybe even get to doing some low-level rendering using 3D math, that sort of thing (think like orginial Wolfenstein level pseduo-3D kind of stuff). So, I'm not even really terribly interested in hardware accelerated 3D at this point (or even 3D at all yet, I'm perfectly fine just doing 2D as simply doing graphics period is novel enough for me, haha!).

You'd be better off just messing around with OpenGL then if you aren't actually trying to make graphics. A simple exercise you might try is to make a simple OBJ loader/renderer.

i see

thanks for replying so fast :)

If you really want to know what you're doing use ++i in your for loops instead of i++!

Problem I got to do, but I slightly confused and I am wondering if I am on the right track.

I am using VS express

So far I got



I need to
A. Write a statement that includes the header files fstream, string, and iomanip in this program.
B. Write statements that declare inFile to be an ifstream and outFile to be an ofstream variable.
C. The program will read data from the file inData.txt and write output to the file outData.txt. Write statements to open both of these files, associate inFile with inData.txt, and outFile with outData.txt.
D. Suppose that the file inData.txt contains the following data:
10.20 5.35
15.6
Randy Gill 31
18500 3.5
A
The numbers in the first line represent the length and width of a rectangle.The number in the second line represent a radius of a circle.The third line is a first name, last name, and age.The fourth line is a savings account balance, as well as an interest rate.The fifth line contains an Uppercase letter between A and Y(inclusive). Write statements so that after the program executes, the contents of the file outData.txt are shown below. If necessary, declare additional variables. Your statements should be general enough so that if the content of the input file changes and the program is run again (without editing and recompiling), it outputs the appropriate results

Rectangle:
Length = 10.20, width = 5.35 , area = 54.57, parameter = 31.10

circle:
Radius = 15.60, area = 764.54, circumference = 98.02

Name: Randy Gill age: 31
Beginning balance = $18500.00, interest rate = 3.50

Balance at the end of the month $18553.96

The character that comes after A in the ASCII set is B.

It looks like you've done A and B but not C or D yet. I guess you did part of C, but you haven't read the input file yet so you can't do anything for part D until you do.

You should probably read up a bit on ifstream: http://www.cplusplus.com/reference/fstream/ifstream/ifstream/
 

RustyO

Member
I posted this over on Stack Overflow over week ago, but no bites, and despite all my google-fu, can't seem to find a solution. It's not a show stopper, so not too stressed, just a bit frustrating.

I am having issues with a C# WinForms application displaying the correct font when running in Wine. According to this link, it should be a simple case of installing the font on the Mac, or adding to the Wine bottled package.

http://winebottler.kronenberg.org/wp/faqs/category/programs/

But despite following the above, when running the application, a different font is displayed. The font I am using is Moire, a standard true type font with Windows.

The application itself is trival. A single form with a few labels displaying the font. (Regular, bold, italic etc)

I installed the font on the Mac by double clicking the file and "Install Font" and all went as expected.The font has also been copied to locations:

  • /Library/Fonts/Moire-Regular.ttf
  • /Macintosh HD/System/Library/Fonts/Moire-Regular.ttf
  • /User/Library/Application Support/~~appid~~/drive_c/windows/Fonts/Moire-Regular.ttf
  • ~~app~~/Contents/Resources/wineprefix/drive_c/windows/Fonts/Moire-Regular.ttf

I've tried copying it wherever I can figure out fonts live, embedding the font and using it via PrivateFontCollection, programtically setting it at runtime, But still no joy...

Has anyone done something like this with Wine / Ubuntu etc?
 
They can do just about anything. I wrote an installer once that configured a networked data store targeting up to five possible database vendors and performed a full in-situ migration from three previous product levels if one was detected. There's no end of what kind of madness you can stuff into an installer, you just have to weigh whether or not the automation is going to be worthwhile to your intended userbase.
Wow, that's quite the installer project. All possible through .msi or did you need a custom solution/Installshield?

They might have uninstall functionality and they might register services.
Wouldn't that still be querying the registry or filesystem somewhere? Still only about three months in to full time Windows development.

You mean return over_limit ?

Where would that go in the code?

Code:
def over_limit(speed, limit):
    if speed > limit:
        over_limit(speed - limit)
        print ("You are over the speed limit by: " + str(over_limit))
    elif speed <= limit:
        print ("You are maintaining the speed limit.")
    
def main():
    limit = ask_limit()
    speed = ask_speed()
    over_limit = (speed, limit)
main()

There are three places in this code snippet where over_limit is used; a function definition, function call, and a variable (frankly, it's surprising to me that Python didn't issue an error. That would have been super helpful.). While all three are different, functions follow the syntax of <function_name>() while variables follow the syntax of <variable_name> = <some expression>. Check to make sure all over_limit's are using the right syntax.
 

Dereck

Member
Code:
public static int fillFibArray (int [] fib ) {
	fib [0] = 1;
	fib [1] = 1;
	for(int i = 2; i < fib. length ; i++) {
	fib [i] = fib[i -1] + fib[i -2];
	}
	return fib . length ;
	}
	public static void main ( String [] args ) {
	int n = 42;
	int [] arr = {2, 4, 6, 8, 10, 12, 14, 16, 18};
	n = fillFibArray (arr );
	System .out . println ("n = " + n);
	for(int i = 0; i < arr. length ; i++) {
	System .out . println ("arr [" + i + "] = " + arr [i]);
	}
	}
	}
Guys, could you please help me understand why this code is outputting this?

n = 9
arr [0] = 1
arr [1] = 1
arr [2] = 2
arr [3] = 3
arr [4] = 5
arr [5] = 8
arr [6] = 13
arr [7] = 21
arr [8] = 34

I get that Fib has 9 elements in it, but when it comes down to arr[0] - arr[8], how exactly are we getting those numbers? I get that I'm supposed to be subtracting 3 somewhere...
 

Somnid

Member
Wouldn't that still be querying the registry or filesystem somewhere? Still only about three months in to full time Windows development.

To be honest I don't know what it does under the hood but you use the "net install" command. At it's core even the registry is a database file that you write to but you probably wouldn't do that manually so it depends how broad that statement is to be taken.
 

Rush_Khan

Member
I get that Fib has 9 elements in it, but when it comes down to arr[0] - arr[8], how exactly are we getting those numbers? I get that I'm supposed to be subtracting 3 somewhere...

The value of the current index equals the sum of the previous two (like Fibonacci sequence).

By default, Fib[0] and Fib[1] equal 1. In the code, there is a loop iteration with variable i.
Fib = Fib[i-1] + Fib[i-2].

Edit: I should mention that, in the main, you are replacing the original elements of arr (2,4,6,8,etc.) with the Fibonacci sequence when using the function fillFibArray(arr). n contains the number of elements you have (you initiliased this to 42 but you don't really need to do this, just initialise n after declaring arr and set it equal to fillFibArray(arr).).
 

SOLDIER

Member
Still no luck. I think I need to get back to the drawing board, but the assignment is due today.

This is what I need to accomplish via Python:

Design a program that calculates and displays the number of miles per hour over the speed limit that a speeding driver was doing. The program should ask for the speed limit and the driver's speed. Validate the input as follows:

-The speed limit should be at least 20, but not greater than 70.

-The driver's speed should be at least the value entered for the speed limit (otherwise the driver was not speeding).

Once correct data has been entered, the program should calculate and display the number of miles per hour over the speed limit that the driver was doing.

I know the subject is Input Validation but I can't get any examples working correctly.
 

Tamanon

Banned
OK, break it down into parts first. That's the easiest way to understand programming, especially at first.

Start with the validation part. Write a function that validates input. Test it with inputs that are both within the range specified and outside it.
 

SOLDIER

Member
Tried to build it from scratch:

Code:
def main():
    limit = 0
    driver = 0
    over_limit = (limit - driver)
main()



def ask_limit():
    limit = float(input("Enter the speed limit: "))
    return limit
def ask_driver():
    driver = float(input("Enter the driver's speed: "))
    return driver
def over_limit():
    if driver > limit:
        print ("You are over the speed limit by: " + str (over_limit))
    elif limit <= driver:
        print ("You are maintaining the speed limit.")

Doesn't ask me for anything now. I still don't know what I'm doing wrong, and it's frustrating me.
 
Top Bottom