#Hello Can Anybody help with my C program

172 messages ยท Page 1 of 1 (latest)

crisp pollenBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

scenic swallow
#

Wdym by "does not work"?

modern pendant
scenic swallow
#

I mean first of all if your input is 33 + 22 / 20 = then you don't have 4 numbers and 4 operator like your code asks you to input

#

If I input e.g. 33 + 22 + 20 + 20 = then I get the outcome 75 which is correct

#

*incorrect

modern pendant
#

Oh so its actually a working code?

scenic swallow
#

No, just realized that 33 + 22 + 20 + 20 doesn't add up to 75 ๐Ÿ˜…

#

Also apparently 75 is always the output, regardless of what operators and operands you input

modern pendant
#

why is that?

scenic swallow
#

Idk, but your code is really weird in that you somehow try to account for precedence but then don't really care about it, e.g. if the first operator is a + then you perform that + on the first and second number, regardless of if the second operand is a e.g. a * which would mean you'd need to wait for the 2nd * 3rd operator to add that multiplied value to the first_num rather than what you're doing

#

In general your code has a lot of duplicate code and is very hard to extend/fix stuff in because you have so many if/else if/else stuffs and so many different variables

modern pendant
#

Can you help plz.. I have to get this done within a hour and a half ...sadcat

#

The a lot of variables come from the instruction which the teacher gave.. I have to follow it all

scenic swallow
#

I mean I can help you to get onto the correct path but really to do this while staying sane we basically have to scratch your entire code.

Also I'm not writing the code for you and neither is anyone here.
There's a nice saying

Your lack of planning is not my emergency

OH, and I didn't even read the instructions, yet.
Just a quick skim and nevermind, you apparently really do need to do it cursed like that and don't need to scratch your entire code.
Anyways, I'll be out for a joint and then read through the assignment.

limber adder
#

this assignment seems a bit too challenging for beginners honestly imho; best way to do it would be recursive descent parsing but by no means that's a "beginner" topic ๐Ÿ™ƒ

scenic swallow
#

Also we don't even know from what week that homework is.
I'd say it's okay for like week 3

#

Maybe even week 2

limber adder
scenic swallow
# scenic swallow Maybe even week 2

I say that because the concepts required are really simple:

  • individual variables rather than any data structure(s)
  • only if/else, no loops
  • how to read in the input is already given, all you need to do is parse the numbers and operands
scenic swallow
#

*Oh yeah, also when I say "week 2" I mean week 2 of uni.
If OP is still in school then that'd be more like week 8 or so

#

I had Java in school for 2.5 years (last semester of 10th, then 11th and 12th grade)
In my mandatory 1st semester uni Java course we surpassed my entire Java knowledge I had from school in week 7 or 8

modern pendant
#

cool

topaz mulch
#

cuz it kinda looks like it lmao

modern pendant
limber adder
modern pendant
#

But it stil doesnt work

limber adder
limber adder
# topaz mulch i would imagine so

not sure what are the implications for chatgpt-assisted code at least for creating the initial drafts that I'd have to check with my professors ://

topaz mulch
#

are y'all in uni?

limber adder
#

a butt ton of my assignments have all been in C ๐Ÿ‘€

modern pendant
#

So can you help my code...

topaz mulch
#

that's good

topaz mulch
limber adder
topaz mulch
#

but c isn't oop

limber adder
topaz mulch
#

oop is an industry standard or being weak at it?

limber adder
#

man we really hijacked this thread ๐Ÿ˜‚

topaz mulch
#

nice

#

lmao

#

msg to OP:
do you want us to rewrite your code for you?

#

and you didn't answer my first question

limber adder
#

I downloaded OP's code and gcc'ed it and it's freezing after accepting input for some reason ๐Ÿ‘€

topaz mulch
#

strange

#

lemme look at it

modern pendant
#

nah it wasn't gpt

#

I have the same problem

#

if I input 4 numbers it sill gives a wrong answer

topaz mulch
#

maybe try using switch statements

limber adder
#

I think the scanf is being "misused" as a preliminary hunch...

topaz mulch
#

yes

#

i thought the same thing

modern pendant
#

thanks

limber adder
#

also @modern pendant make sure you add an additional percent sign like so:
printf("The numbers must be integers and the operators must be +, -, *, /, or %%!\n")
Helps to get rid of gcc warning ๐Ÿ˜„

modern pendant
#

oh that was also the problem thank you

scenic swallow
#

I just looked through it and what I found is that you made a mistake when reading the given real language algorithm.

9.
If operator_one is *, /, or %
a) If operator_one is *
(1) Multiply the first_num and the second_num, and store it in firstSecondOutcome
b) Else if operator_one is /
(1) Divide the first_num and the second_num, and store it in firstSecondOutcome
c) Else
(1) Find the remainder of the first_num and the second_num, and store it in firstSecondOutcome
d) Set firstOperatorFlag with value 2
10. Else if operator_two is * /, or %        <-- here you went wrong
a) If operator_two is *      
if (operator_one == '*' || operator_one == '/' || operator_one == '%') {
    if (operator_one == '*') {
        firstSecondOutcome = first_num * second_num;
    } else if (operator_one == '/') {
        firstSecondOutcome = first_num / second_num;
    } else {
        firstSecondOutcome = first_num % second_num;
    }
    firstOperatorFlag = 2;
} else /*  <-- here you should've written 'else if (operator_two == '*' || operator_two == '/' || operator_two == '%' { ... */ {
    ...
}
limber adder
#

but 1+2+3+4 is giving me 7 tho

modern pendant
#

i'll be back within 15 minutes, currently doing it again rn

limber adder
limber adder
limber adder
# scenic swallow I just looked through it and what I found is that you made a mistake when readin...

do you mean?

  // Check for the first operator precedence
  if (operator_one == '*' || operator_one == '/' || operator_one == '%') {
    if (operator_one == '*') {
      firstSecondOutcome = first_num * second_num;
    } else if (operator_one == '/') {
      firstSecondOutcome = first_num / second_num;
    } else {
      firstSecondOutcome = first_num % second_num;
    }
    firstOperatorFlag = 2;
  } else if (operator_two == '*' || operator_two == '/' ||
             operator_two == '%') {
    if (operator_one == '+') {
      firstSecondOutcome = first_num + second_num;
    } else {
      firstSecondOutcome = first_num - second_num;
    }
    firstOperatorFlag = 2;
  }
crisp pollenBOT
#

@modern pendant Has your question been resolved? If so, type !solved :)

limber adder
#

๐Ÿ™ƒ

tedliosu@victus-ted:~/Downloads/programs/from_discord$ ./rando_prog 
Welcome to a working Calculator~!
You will be providing four numbers and four operators
The numbers must be integers and the operators must be +, -, *, /, or %!
Remember that the last operator MUST be an equal sign ~
Please enter the expression below: 
33+22/20+0=
The outcome for the expression came out to be 55
Thank You
#

man this program is cursed and convoluted fr fr

crisp pollenBOT
#

@modern pendant

Please Do Not Delete Posts!

Please don't delete forum posts. They can be helpful to refer to later and other members can learn from them. In the future you can use !solved to close a post and mark a post as solved.

modern pendant
limber adder
limber adder
modern pendant
#

!so;ved

#

!solved

crisp pollenBOT
#

Thank you and let us know if you have any more questions!

This thread is now set to auto-hide after an hour of inactivity

topaz mulch
#

oh ok it's solved

limber adder
topaz mulch
#

if anybody is interested i remade this in c++ with switch statements

topaz mulch
#

do you want to see it?

limber adder
scenic swallow
topaz mulch
#

yes

limber adder
#

what advantages do C++ serve here over C btw?

#

cuz I can't see one tbf

scenic swallow
#

It's just easier to get something running.

Best example is std::vector

#

Whereas for C you'd have to write your own linked list + insert + remove + whatever you need

limber adder
topaz mulch
#

actually i'm using visual studio

topaz mulch
#

so i dunno if it will work with g++

limber adder
limber adder
topaz mulch
#

#include <iostream>
#include <string>
#include <sstream>

#
#include <iostream>
#include <string>
#include <sstream>

void mainScreen();
int evaluateExpression(int num1, char op1, int num2, char op2, int num3, char op3, int num4);

int main() {
    mainScreen();
    return 0;
}

void mainScreen() {
    std::cout << "Welcome to the Calculator!" << std::endl;

    std::cout << "Please enter an expression of up to 4 digits (e.g., 5 + 3 * 2 + 3=): ";

    std::string input;
    std::getline(std::cin, input);

    std::istringstream iss(input);
    int num1, num2, num3, num4;
    char op1, op2, op3, equals;

    iss >> num1 >> op1 >> num2 >> op2 >> num3 >> op3 >> num4 >> equals;

    int result = evaluateExpression(num1, op1, num2, op2, num3, op3, num4);
    std::cout << "Result: " << result << std::endl;
}


int evaluateExpression(int num1, char op1, int num2, char op2, int num3, char op3, int num4) {
    int result;
    switch (op2) {
    case '*':
        result = (op1 == '+') ? num1 + num2 * num3 : num1 - num2 * num3;
        break;
    case '/':
        result = (op1 == '+') ? num1 + num2 / num3 : num1 - num2 / num3;
        break;
    case '%':
        result = (op1 == '+') ? num1 + num2 % num3 : num1 - num2 % num3;
        break;
    case '+':
        result = (op1 == '+') ? num1 + num2 + num3 : num1 - num2 - num3;
        break;
    case '-':
        result = (op1 == '+') ? num1 + num2 - num3 : num1 - num2 + num3;
        break;
    }

    switch (op3) {
    case '*':
        result = (op2 == '+') ? result + num4 : result - num4;
        break;
    case '/':
        result = (op2 == '+') ? result + num4 : result - num4;
        break;
    case '%':
        result = (op2 == '+') ? result + num4 : result - num4;
        break;
    case '+':
        result += num4;
        break;
    case '-':
        result -= num4;
        break;
    }
    return result;
}
limber adder
topaz mulch
#

wry guys i need to go i'll be back in a bit

topaz mulch
scenic swallow
limber adder
scenic swallow
limber adder
scenic swallow
#

but -3 is wild

limber adder
topaz mulch
#

lmao looks like it's not working

limber adder
#

LOL

topaz mulch
#

nvm i give up

#

๐Ÿคฃ

limber adder
topaz mulch
#

ye

#

wait imma try to fix it actually

limber adder
limber adder
# topaz mulch rly?

or something idk I'm just trying to practice testing as per advice from father ๐Ÿ˜„

limber adder
# topaz mulch rly?

do you mind if I write tests and you do the actual logic? sorry I'm terrible with parsing stuff lol

#

and I'm also terrible with C++

scenic swallow
limber adder
# scenic swallow My gosh, haha. I'm in my 4th data structure now. First I tried with a vector, t...

how's this thus far (without the asserts?)

tedliosu@victus-ted:~/Downloads/programs/from_discord$ ./unit_tests.sh
Testing 1+2+3+4=
Welcome to the Calculator!
Please enter an expression of up to 4 digits (e.g., 5 + 3 * 2 + 3=): Result: 10
Testing 4*3*2*1=
Welcome to the Calculator!
Please enter an expression of up to 4 digits (e.g., 5 + 3 * 2 + 3=): Result: -3
Testing 5*8-9-0=
Welcome to the Calculator!
Please enter an expression of up to 4 digits (e.g., 5 + 3 * 2 + 3=): Result: 6
Testing 4-3+2+1=
Welcome to the Calculator!
Please enter an expression of up to 4 digits (e.g., 5 + 3 * 2 + 3=): Result: 0
scenic swallow
#

Btw, I'm finished

#

;compile | 1 + 2 * 4 / 3 - 1 - 1 - 1 - 1 =

#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
#include <deque>

int eval_expr(std::deque<int> nums, std::deque<char> ops) {
    static int i{};

    while (ops.front() != '=') {
        int n1 = nums.front();
        nums.pop_front();
        char op = ops.front();
        ops.pop_front();
        int n2 = nums.front();
        nums.pop_front();

        switch (op) {
            case '*':
                nums.push_front(n1 * n2);
                break;
            case '/':
                nums.push_front(n1 / n2);
                break;
            case '%':
                nums.push_front(n1 % n2);
                break;
            case '+':
                nums.push_front(n2);
                return n1 + eval_expr(nums, ops);
            case '-':
                nums.push_front(-n2);
                return n1 + eval_expr(nums, ops);
        }
    }

    return nums.front();
}

int main() {
    std::cout << "Welcome to the Calculator!" << std::endl;
    std::cout << "Please enter an expression ending with '='";

    std::string input;
    std::getline(std::cin, input);
    
    /* Code from https://stackoverflow.com/a/83481 . Removes all spaces (wasn't required) */
    /*
    std::string::iterator end_pos = std::remove(input.begin(), input.end(), ' ');
    input.erase(end_pos, input.end());
    */

    std::istringstream iss(input);
    std::deque<int> nums;
    std::deque<char> ops;

    for (;;) {
        int n;
        char c;
        iss >> n >> c;
        nums.push_back(n);
        ops.push_back(c);

        if (c == '=') break;
    }

    std::cout << std::endl << input << " " << eval_expr(nums, ops) << std::endl;
}
feral deltaBOT
#
Program Output
Welcome to the Calculator!
Please enter an expression ending with '='
1 + 2 * 4 / 3 - 1 - 1 - 1 - 1 = -1
limber adder
scenic swallow
#

Arbitrary amount of inputs even

#

Python would be the easiest by far

#

;compile | 1 + 2 * 4 / 3 - 1 =

equation = input("Please enter an expression ending with '=': ")
print(f"{equation[:-2]} = {eval(equation[:equation.find('=')])}")
feral deltaBOT
#
Program Output
Please enter an expression ending with '=': 1 + 2 * 4 / 3 - 1 = 2.6666666666666665
limber adder
#

LMAO

scenic swallow
#

could even enforce integer division with a simple replace

#

;compile | 1 + 2 * 4 / 3 - 1 =

equation = input("Please enter an expression ending with '=': ")
print(f"{equation[:-2]} = {eval(equation.replace('/', '//')[:equation.find('=')])}")
feral deltaBOT
#
Program Output
Please enter an expression ending with '=': 1 + 2 * 4 / 3 - 1 = 2
limber adder
# scenic swallow First result is correct, all others are wrong

How's this now?

tedliosu@victus-ted:~/Downloads/programs/from_discord$ ./unit_tests.sh
Testing 1+2+3+4=
10 was expected; PASS
Testing 4*3*2*1=
24 was expected, but -3 was actual; FAIL
Testing 5*8-9-0=
31 was expected, but 6 was actual; FAIL
Testing 4-3+2+1=
4 was expected, but 0 was actual; FAIL
scenic swallow
#

How's what?

limber adder
topaz mulch
#

hey guys

scenic swallow
#

For an actual testing framwork? Bad, because you need to write your own shell script.
For this very case it's okay, however I would probably let it randomly choose operands and operators, evaluate these and then check that the result of your program matches your evaluation

limber adder
topaz mulch
#

sure why not

scenic swallow
limber adder
# topaz mulch sure why not
#!/bin/bash

# Declare our array of test expressions
test_exps=(
           "1+2+3+4"
           "4*3*2*1"
           "5*8-9-0"
           "4-3+2+1"
          )
name_of_prog="rando_prog_itex"
name_of_exten=".cpp"
result_field_num="19"


# DON'T ALTER ANYTHING BELOW THIS LINE; UNLESS IF YOU KNOW
#    EXACTLY WHAT YOU'RE DOING.

# First argument is expected, second argument is actual :D
assert_expected () {

    if [[ "$1" -eq "$2" ]]; then
        echo "$2 was expected; PASS"
    else
        echo "$1 was expected, but $2 was actual; FAIL"
    fi

}

g++ "${name_of_prog}${name_of_exten}" -o "$name_of_prog"

for expressn in "${test_exps[@]}"; do
    echo "Testing $expressn="
    actual_ans=$(echo "${expressn}=" | "./$name_of_prog" | cut -d" " -f"$result_field_num" | tr -d "\n")
    expected_ans="$(echo "${expressn}" | bc)"
    assert_expected "$expected_ans" "$actual_ans"
done

# Cleanup
rm -rf "$name_of_prog"
topaz mulch
#

i don't know anything about bash really, but i guess this will test my program

limber adder
limber adder
topaz mulch
#

nvm my program was broken anyway

#

i have a new version now

limber adder
topaz mulch
#

it even throws an error when there is a modulo or adivision by zero

limber adder
topaz mulch
#

wait

#

i found an error

#

i need to take into account PEMDAS

#

should i make it so it uses parenthesis?

limber adder
topaz mulch
#

ok

#

so here is my final version

#

ignore the" c++"

#

ok imma stop here

limber adder
# topaz mulch ok imma stop here

LGTM:

tedliosu@victus-ted:~/Downloads/programs/from_discord$ ./unit_tests.sh 
Testing 1+2+3+4=
10 was expected; PASS
Testing 4*3*2*1=
24 was expected; PASS
Testing 5*8-9-0=
31 was expected; PASS
Testing 4-3+2+1=
4 was expected; PASS
Testing 3*4/9+9=
10 was expected; PASS
Testing 4*7+2+64=
94 was expected; PASS
Testing 34*6*1+3=
207 was expected; PASS
Testing 2-5+43-4=
36 was expected; PASS
Testing 3-54*43*43=
-99843 was expected; PASS
Testing 4-2*65/4=
-28 was expected; PASS
Testing 54-3-47-2=
2 was expected; PASS
topaz mulch
#

cool

#

try it with more

limber adder