/tech/ - Tech

Technology.

catalog
Mode: Reply
Name
E-mail
Subject
Message

Max message length: 8192

Files

Max file size: 20.00 MB

Max files: 3

Password

(used to delete files and postings)

Misc

Remember to follow the rules


(503.48 KB 934x1000 daily_programming.png)
Daily Programming Thread Comrade 01/27/2020 (Mon) 18:13:02 No. 17
What are you working on, /roulette/?
Someone tell me why this script won't work as a hotkey: [code]pactl set-sink-input-volume $(pactl list sink-inputs | grep -B 25 $(xdotool getwindowpid $(xdotool getwindowfocus)) | grep 'Input' | cut -d '#' -f2) -10%[/code]
>>18 Hotkey in what?
>>19 Xfce, Openbox, everything I've tried so far. For some reason it works at a terminal command but fails to do dick as a keyboard shortcut.
>>18 Execute this shit through shell Either: >sh -c "pactl set-sink-input-volume $(pactl list sink-inputs | grep -B 25 $(xdotool getwindowpid $(xdotool getwindowfocus)) | grep 'Input' | cut -d '#' -f2) -10%" Or: >bash -c "pactl set-sink-input-volume $(pactl list sink-inputs | grep -B 25 $(xdotool getwindowpid $(xdotool getwindowfocus)) | grep 'Input' | cut -d '#' -f2) -10%"
>>20 - did you add the shebang to the script? - have you made the script executable? - maybe some part of your command is relying on an environment variable that's present only in your shell session
Working on and off on a Python module that combines cURL and Tor into a simple interface. It's very nice for writing web scrappers, I have written a ton of them by now, anything from searching through my local library from CLI to scripts periodically checking for good deals on books I want to buy. I'll put it on some repo host once it becomes something more than a permanently mutating prototype.
>>18 >>21 >>22 Oh shit, I'm a dummy. I didn't think to save the script as a file and try running the file on command. Guess keyboard shortcuts can't deal with long strings of naked shell script.
So I've got a grep output of varying amounts of numbers that I'd like to store as a variable so that I can perform further operations on it. Basically I want to check the number of lines/numbers and if it's only one, do this with; if it's more than one, do something else with it. What's the best way to go about doing this in shell scripting? I thought about using wc but that doesn't seem to work well on variables (tries to open each number as a file instead of parsing the string of numbers). Is an array a better idea?
>>25 >>18 >>24 Actually, let me just explain what I'm trying to do here and maybe that'll help more. I'm trying to come up with a way to alter volume on a per-program basis with hotkeys by focusing on the active program/pulseaudio sink for the currently focused window. First, I'm using xdotool to get the process ID of the focused window. That's xdotool getwindowpid $(xdotool getwindowfocus). Then, I use the process ID to query pulseaudio for the associated sink ID the process's audio client is using. Here is where a snag arises. It turns out some processes (such as web browsers with multiple audio tabs open) can be using multiple audio clients. I use grep to return a list of these audio client IDs. Now somehow I need to figure out a way to select only the audio client ID associated with the current browser tab.
>>25 #!/bin/bash get_random_numbers() { shuf -i1-100 -n$(shuf -i1-3 -n1) } output=$(get_random_numbers) if [[ $(echo "$output" | wc -l) -eq 1 ]]; then echo "There's only one number and it is $output." else echo "There are multiple numbers." fi
>>27 Alternatively you can also use a so-called herestring (bash specific, not part of POSIX) to make the variable the input of wc: [[ $(wc -l [orange][orange][orange] "$output") -eq 1 ]]
>>28 It's supposed to be three smaller-than symbols, not <<<
what the fuck>>29 >>28
(defun G1 (i11 i12 f1) (+ i11 i12 f1)) (defun G2 (i21 i22 f20) (+ i21 i22 f20))
>>31 (defun G1 (i11 i12 f1) (+ i11 i12 f1)) (defun G2 (i21 i22 f2) (+ i21 i22 f2)) (defun i11 (a11 g1) (* aleph11 g1)) (defun i12 (a12 g2) (* a12 g2)) (defun i21 (a21 g1) (* a21 g1)) (defun i22 (a22 g2) (* a22 g2))
e=181021504832735228091659724090293195791121747536890433 u(f,m)x=i(m(x), [],let(a,b)=f(x) in(a:u(f,m)b)) (v,h)=(foldr(\x(y )->00+128*y+x)0,u( sp(25),((==)""))) p::(Integer,Integer )->Integer -> Integer --NotInt p(n,m)x =i(n==0 ,1,i(z n ,q(n,m)x, r(n,m)x)) i(n,e,d )=if(n) then(e) else (d) --23+3d4f (g,main ,s,un)= (\x->x, y(j),\x->x*x,unlines)--) j(o)=i(take(2)o== "e=","e="++t (drop(4-2)o),i(d>e,k,l)o) l=un.map (show.p (e,n).v.map( fromIntegral{-g-}.fromEnum)).h k=co.map(map(toEnum .fromIntegral ).w.p(d,n). read).lines (t,y)=(\ (o:q)-> i(o=='-' ,'1','-' ): q,interact) q(n,m)x= mod(s( p( div(n)2, m{-jl-})x) )m--hd&&gdb (r,z,co) =(\(n, m)x->mod(x*p(n-1, m)x)m,even ,concat)--6 (w,sp)=( u(\x->( mod(x)128,div(x )128),(==0 )),splitAt) d=563347325936+1197371806136556985877790097-563347325936 n=351189532146914946493104395525009571831256157560461451
I think I want to write an xmpp client library. In C so that it'd be easily usable from most other languages.
r8 my poor's man xxd $ shuf -n 1 /usr/share/dict/words | shuf -re {0..9} {a..f} --random-source /dev/stdin 2>/dev/null | tr -d $ '\n' | fold -w 2 | rev | xxd -p -r
(128.59 KB 457x645 thumbs_up.png)
>>36 Nice hack!
>>32 Why anon? The whole point of Lisp is to have lists as a free data structure. If you want to do linear algebra, take advantage of this feature. (defun matrix-calc (g1-list g2-list a1 a2) (let* ((g1 (reduce #'+ g1-list)) (g2 (reduce #'+ g2-list)) (i11 (* (car a1) g1)) (i12 (* (cadr a1) g2)) (i21 (* (car a2) g1)) (i22 (* (cadr a2) g2))) (list (cons i11 i12) (cons i21 i22)))) (matrix-calc '(1 2 3) '(4 5 6) '(10 5) '(20 55))
>>38 tbh I was just planning to go through the examples in towards a new socialism step by step and I found common lisp separating function and and data name spaces spiffy Was planning to pull in a matrix library for the next step, but yeah maybe if this goes somewhere it'd be better for it to be self contained
(3.09 MB 1230x1593 3819085.png)
> Rules of /tech/ > Remember that no matter the rules of the board, all global rules apply > Global Rules > Title goes here > Insert rules here. What images are allowed on /tech/?
>>372 Tech is SFW. I don't actually think we have NSFW boards yet.
(1.11 MB 1099x1600 4119250.jpg)
>>373 Thanks for the info. I only asked because in 'boards' there is an obvious *SFW* marking on /leftypol/ and /gulag/ but nowhere else.
>>374 Yeah that wasn't actually our doing. They were there before we got here.
>>17 Interviews, new projects, finishing a front end gig (the bane of my existence, can't fucking wait for it to be fucking over holy fuck), mainting old projects. Fuck front end tbh. I don't get it, all tutorials are baby tier ("this is called a div" I FUCKING KNOW, TEACH ME HOW TO MAKE ACTUAL FUCKING PAGES). I can't into it and I'm going fucking nuts. I was planning on forefitting the project, but I promised myself to finish ONE front end job and I'm like 3/4 of the way.
>>39 >tbh I was just planning to go through the examples in towards a new socialism step by step No problem, I didn't know TaNS dealt with algorithms that much, guess I should really read it >I found common lisp separating function and and data name spaces spiffy It doesn't matter that much IMO, like yeah you can use "list" as a variable name but you have to use funcall to do functional programming, whatever. Common Lisp is pretty ugly compared to Scheme, but I currently learn it too because SBCL + Emacs offer a degree of interactivity I haven't seen in any other language runtime. The fact that you can redefine a function while your program is running or ran into an error is really awesome, and it's a fun development experience. You are also not constrainted to code in a functional style if you don't want to in CL, but you still can. It's one of the most flexible language I know of. Don't be afraid of spending time with Scheme teaching materials though. I still need to go through the Little Schemer one of these days. >Was planning to pull in a matrix library for the next step, but yeah maybe if this goes somewhere it'd be better for it to be self contained I think there is a library like numpy for Common Lisp, but if I were you, I would try to do as much as possible with lists, vectors, functions and macros. Here is a function to call "matrix-calc" with matrices made of lists. [code] (defun mat-calc (i f a) (matrix-calc (append (car i) (list (car f))) (append (cdr i) (cdr f)) (car a) (cdr a))) (equal (matrix-calc '(1 2 3) '(4 5 6) '(10 5) '(20 55)) (mat-calc '((1 2) . (4 5)) '(3 6) '((10 5) . (20 55))) ) [/code] matrix-calc could be defined inside mat-calc with flet/labels as an helper function, that would be the Scheme way of doing stuff like this. A closure, as they call it.
what does tech think of nim? https://nim-lang.org/
>>386 >Garbage collection I'm good. GC is fine as long as your program doesn't rely on continuous user input. I'm messing around with this at the moment: https://ziglang.org/ Nim looks like it's much more mature tho, Zig still a work in progress. There's also Jai which might turn out to be a complete meme if it releases before temps go up 5C. Either way, give me arbitrary compile-time execution, manual memory management, and C interoperability, and I'll bite.
(5.26 MB 3508x4961 3758819.jpg)
To have a full thread view with relative navbar and sane layout, an overflow change is needed. $ cat bunker-thread.css nav { position: relative; } .divMessage { margin: 0px; } #mainPanel { overflow: visible; }
>>390 I like controlling the memory allocation as well. FWIW the garbage collector can be disabled; then you use alloc/dealloc. The only thing I found annoying is the loose-casing so that VK_NULL_HANDLE = VkNullHandle = Vknullhandle = VK_nullHandle = Vk_n_u_ll_han_DLE ... and so on *sniff*.
Really fucking tired of programming bros. Nearly done with school and can't give a fuck about the classes I'm taking. So I'm just applying to jobs, and basically hoping I'll give a shit about the awful frameworks they use. I like data structure stuff, I like a lot of things in programming, but I hate all the bloat, complexity, and brokenness of big software. All web frontend stuff is cancer. Cloud services are cancer. >>383 TANS describes the algorithm for labor time calculation, but not for five year plans. Cockshott's plan algos are in some other paper, and on his github.
(333.25 KB 1366x1536 fun-programming.jpg)
>>396 The problem is probably that you are reading stupid shit like ``cybernetic'' socialism.
>>398 go back to /g/
>>396 I'm in a similar situation, degree in mathematics but I'm so tired of it, I don't want to fail but I find so little motivation to do any of the work I don't know what went wrong. Might be because you're done with the system, rather than done with programming. I can't wait to stop being forced to learn shit I don't care about at all, at least after work you can go home and forget about it. Currently working on some simulations of instruments, can't share any code cos would dox me, but thinking about rewriting it in C/C++ for speed when I have time this summer, would anyone be interested in that?
OpenCL drivers updated, pull latest source, recompile retune for GPU grumble
>>395 >Loose casing I didn't even know that was a thing. I wish I never knew, it's horrific!
>>428 Watcha making wif OpenCL?
What text editor do you use for programming? I am learning emacs.
>>819 Vim master race
>>819 Slowly transferring my workflows towards a vim system, it seemed silly at first but the more I've used it the more I see how invaluable of a program it is. Latex is resisting the migration currently though because I can't get the compilation to work nicely with my wm amongst other things
(239.10 KB 512x512 emacs.png)
>>819 GNU emacs, of course. I can't imagine computing without it.
(21.18 KB 474x504 rt345345.jpeg)
Hello /DPT/. I am finding myself a bit bored during the pandemic and I have taken it upon myself to attempt to learn the C programming language. Up to this point I have had no real issues with anything. I have learned about Variables, sets, how to group things together, how to get user input with scanf; doing math on numbers. I understand libraries and how we need to pull them in order for C to understand what is going on, but, I seem to have hit a slight snag: #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int x[] = {t, y, z}; scanf("%d%d%d", x[0], x[1], x[2]); printf("%d%d%d", &x); return 0; } This is a simple program I am attempting to write in which the program will gather input from the user and assign them to variables in the array and then print those variables; Basically I am asking how you make if so you can assign values to variables in an array as opposed to having to write out each independent variable and scanf for each variable on its own line, which can be tedious. Thanks for your help!
>>925 I think you need to do scanf("%d%d%d", &x[0], &x[1], &x[2]); scanf needs a pointer to the memory location to store the value, whereas you are passing in the actual values in the array.
>>925 What do you mean when you say "sets"? Do you mean arrays? You can't write out the array as it is, you will have to go through its elements one-by-one, either by writing it out manually or by using a loop. scanf needs pointers as its arguments, you will want something like this: scanf("%d%d%d", &x[0], &x[1], &x[2]); This will accept one number per line, but if you want to enter it on a single line, you will have to put some kind of separator between the format specifiers. For example, "%d-%d-%d" will work as expected with 1968-05-02 but on a non matching input it only do its best effort. 1--5 will be interpreted as x[0]=1 x[1]=-5 and x[2] will not be changed, 1.2.3 will only set x[0] to 1, etc. Using space is a special case, it will match any number of consecutive spaces. Hope this helps!
>>926 I tried this and gcc was still spitting our errors at me. >>927 When I say sets I mean that I understand that int x; is a container for the value of x. Sorry I should have been more specific. So I do need pointers for scanf in an array? Ok, that helps, but, I still do not understand: Can I not use variables for an array? That what If I wanted to input a value with scanf to assign to a variable found inside the array? Is that not possible? This is the error I am getting withy gcc: arrays.c:7:13: error: ‘t’ undeclared (first use in this function) int x[] = {t, y, z}; ^ arrays.c:7:13: note: each undeclared identifier is reported only once for each function it appears in arrays.c:7:16: error: ‘y’ undeclared (first use in this function) int x[] = {t, y, z}; ^ arrays.c:7:19: error: ‘z’ undeclared (first use in this function) int x[] = {t, y, z}; ^ arrays.c:8:10: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=] scanf("%d%d%d", x[0], x[1], x[2]); ~^ ~~~~ arrays.c:8:12: warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘int’ [-Wformat=] scanf("%d%d%d", x[0], x[1], x[2]); ~^ ~~~~ arrays.c:8:14: warning: format ‘%d’ expects argument of type ‘int *’, but argument 4 has type ‘int’ [-Wformat=] scanf("%d%d%d", x[0], x[1], x[2]); ~^ ~~~~ arrays.c:9:11: warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘int (*)[1]’ [-Wformat=] printf("%d%d%d", &x); ~^ ~~ arrays.c:9:13: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=] printf("%d%d%d", &x); ~^ arrays.c:9:15: warning: format ‘%d’ expects a matching ‘int’ argument [-Wformat=] printf("%d%d%d", &x); Thank you!
>>930 You always need pointers for scanf. When you write down a variable in itself, it means the variable's value. scanf needs the variable's address, so it knows where to store the value it has read in. When you write down "int x[] = {t, y, z};" it means that you want an array of three elements, where the zeroth element is the value of t, the first is the value of y and the second is the value of z. Since neither of these variables exists in your program, the compiler does not understand your program. If you were to write &ŧ instead of t, the pointer of t would be the zeroth element of the array, but still as a value. If you want to store variables in an array, you can do so as pointers, but you will have to handle the additional indirection (going from pointer to value) yourself. Consider this example: #include [orange]stdio.h> int main() { int t = 7; int x[] = {0, t, 0}; printf("Initially: %d/%d/%d\n", x[0], x[1], x[2]); /* Read in user input. */ scanf("%d-%d-%d", &x[0], &x[1], &x[2]); /* Print out values. */ printf("User input: %d/%d/%d\n", x[0], x[1], x[2]); /* Print out t */ printf("t: %d\n", t); return 0; } and compare it with this: #include [orange]stdio.h> int main() { int t = 7, y = 8, z = 9; int * x[] = {&t, &y, &z}; printf("Initially: %d/%d/%d\n", *x[0], *x[1], *x[2]); /* Read in user input. */ scanf("%d-%d-%d", x[0], x[1], x[2]); /* Print out values. */ printf("User input: %d/%d/%d\n", *x[0], *x[1], *x[2]); /* Print out t */ printf("t: %d\n", t); return 0; } I hope this actually helps and doesn't confuse you with all the pointer handling...
(20.62 KB 474x400 4tr3t34tg3g5.jpeg)
>>932 The only thing that confuses me is the use of the * rather than the & as a pointer...I am guessing? The other thing that confused me is why you used: int * x[] for your array rather than int x[]. I am guessing it has something to do with the use of the & already? Another thing I don't, really get, is if t, y and z all have values already assigned to them with: int t = 7....etc etc then how do they output the value of whatever the user inputs with scanf? Wouldn't the program just output the values assigned to t? Would I be better off trying to signed values to the integers of t, x, and z respectively and then assigning that to the array? Also, how do I make my code text nice and tiny like that when I am talking code on /tech/? :^) Otherthan that, though, yes this is very helpful.
>>933 You need to wrap your text in [co‌de] [/co‌de] tags: https://bunkerchan.xyz/.static/pages/posting.html The star means pointer. "int * t" means t is an int pointer. "t = &x" assigns the address of x to t, t from now on will point to x. "*t" means whatever t is pointing to. "printf("%d", *t)" will print out the value of x and "*t = 12" will assign 12 to x. Without running it, can you guess what will be the output of the following program? #include [orange]stdio.h> int main() { int x = 17, y = 36; int * p; p = &x; printf("1. x: %d, y: %d, *p: %d\n", x, y, *p); y = *p + y; printf("2. x: %d, y: %d, *p: %d\n", x, y, *p); p = &y; printf("3. x: %d, y: %d, *p: %d\n", x, y, *p); *p = 22; printf("4. x: %d, y: %d, *p: %d\n", x, y, *p); return 0; }
(72.11 KB 160x160 1585325255664.gif)
>>934 "1. x: 17, y: 36, p: 17 2. :x 17, y:53, p: 17 3. x: 17, y: 36, p:36 4. x: 17, y: 36, p: 22" I dunno, that's the best I could do. I wasn't expecting a homework assignment, LOL. I was thrown off by the use of the * next to p in line 12. Other than that the above is what I feel like the program should output. On the upside: The program I was working on I got to actually work now that I understand that I have to define an integer as a pointer. #include [orange]stdio.h> #include [orange]stdlib.h> #include [orange]math.h> int main() { int t, y, z; int * x[] = {&t, &y, &z}; scanf("%d %d %d", &t, &y, &z); printf("%d %d %d\n", *x[0], *x[1], *x[2]); return 0; } Though, this begs the question; A: What is the default pointer for a variable? Like, if I write int x; To define X then what is the default for this? Anything? If that is the case then why do I need to specifically define a variable as an integer? It just seems odd; I hope that made sense. Also, can I define a variable as a different pointer? Like can I define a variable as a character pointer?
>>935 Why would y go back to its previous state before the 3rd print? How did *p end up different from y in the last? I am not sure I understand your question. A pointer is a kind of a type. "int" and "char" are types. There are others, like "double" and "float", and they can have modifiers like "unsigned" or "long".
>>936 My question is: If I have to declare that int p is an integer pointer then why do I not have to do that for everything? do I only have to do it when I am trying to point to something? For example: int x = 17; Does not require a declaration of a type, but, int * p; does. Why is that? >Why would y go back to its previous state before the 3rd print? How did *p end up different from y in the last? So *p will print 22 is what you are saying?
(200.76 KB 710x193 int vs float.png)
>>935 >why do I need to specifically define a variable as an integer (I'm not the anon you were previously talking to but I wanted to try to answer your question anyway) It's because of how the variable is formatted in memory when it's declared. Bits are interpreted by the computer differently depending on their format. This image shows how the computer interprets 32 bits as an int vs how it interprets a different 32 bits as a float, but as you can see, they end up being the same value. >>936 I think this answers your question here too? You need types for pointers because the compiler needs to make sure the types match when those values are used for method calls etc. Let me know if I was way off in understanding your question.
>>938 Ugh I meant to indicate this question >>937 instead of the previous poster in the second half of my comment sorry. clicked the wrong post.
>>938 Oh no, that certainty helps, lol. That answers part of my question. Now the only question I have left is the other half; Why do I NOT need to do that in the case of int x = 17;? why don't I have to define x as an integer in this case? Logically, considering what you just told me shouldn't I have to declare the argument as: int * x = 17; ?
>>937 "int x = 17" means that you are declaring a variable x of the type int. The int is the type there. int * is another type, the int-pointer type.
>>941 > int-pointer Maybe pointer-to-int sounds more English though.
>>941 Oh, ok, ok, see yeah that makes sense. Ok, so I have to declare a type and then if that type is a pointer I have to declare that as well. So, char x = 'y'; Is a character typer But if I wanted to make that a pointer I would need to declare it as char * x = 'y'; ? I mean, I get the concept. I get what you guys are saying. It makes sense, thanks. If it's not to much, I was wondering maybe if some one could help me understand the usage of the "&" better. I understand that it is a pointer but I don't really understand its usage...I guess? If that makes sense? Like If I wrote out: int t, y, z; int * x[] = {&t, &y, &z}; scanf("Integer 1: %d", &t); scanf("Integer 2: %d", &y); scanf("Integer 3: %d", &z); How does the & connect t, y and z to the array of x?
>>943 You can't say "char * x = 'y';", because 'y' is a character literal and not a pointer-to-char. But otherwise you are right. & makes a pointer from a variable. If you have "char c = 'x'", &c will give you back a pointer-to-char that points to c. In your example x will be an array of three pointers: a pointer to t, a pointer to y and a pointer to z. The first two lines is equivalent to this: int t, y, z; int * x[3]; x[0] = &t; x[1] = &y; x[2] = &z; Or if we introduce some more variables to see the types better: int t, y, z; int * x[3]; int * tp = &t; int * ty = &y; int * tz = &z; x[0] = tp; x[1] = ty; x[2] = tz;
(32.58 KB 685x633 int pointer array.png)
>>943 Does this help?
>>947 Yes actually, that makes perfect sense. Thanks for that, lol. So do I even need to define them prior to my array? Like do I even need int x, y, z? I believe gcc was yelling at me about it.
>>949 No, you can just do int *x[3]; and then fill it up later. Ex: int *x[3]; int y = 5; x[1] = &y; printf("%d", *x[1]); That will print 5.
>>950 Thank you for that. Can I ask another question? How do I do math with my arrays? Like how do I add the variables inside my array together? For example.
>>951 Like this?: int x[3]; int y = 5; int z = 10; x[1] = y; x[2] = z; int result = x[1] + x[2]; printf("%d", result); If you wanted to retrieve the values from an array of pointers like we were discussing before, you would just do: int result = *x[1] + *x[2];
>>952 Yes like that, but, I am/was doing that and it keeps giving me an error when I compile it, for example I'll write: #include [orange]math.h> int main() { int t, y, z; int * x[] = {&t, &y, &z}; scanf("Integer 1: %d", &t); scanf("Integer 2: %d", &y); scanf("Integer 3: %d", &z); int result = x[0] * x[1] * x[2]; printf("%d", result); return 0; } and gcc will tell me: Math.c: In function ‘main’: Math.c:13:20: error: invalid operands to binary * (have ‘int *’ and ‘int *’) int result = x[0] * x[1] * x[2]; How am I using an invalid operand? That doesn't make any sense. I was also giving me the same errors before I defined the result as an integer and just wrote the last line as [cpde] printf("%d", x[0] * x[1] * x[2]); [/code]
>>958 Careful with those asterisks! Remember to enclose the value in parenthesis so the compiler knows you want to multiply the value of the pointer: int t, y, z; int * x[] = {&t, &y, &z}; printf("Integer value 1: "); scanf("%d", &t); printf("Integer value 2: "); scanf("%d", &y); printf("Integer value 3: "); scanf("%d", &z); int result = (*x[0]) * (*x[1]) * (*x[2]); printf("%d", result); return 0; Also you should be doing separate print statements instead of putting your prompt in scanf.
(1.77 MB 1080x1082 uhhh.png)
>>959 Well, I think I have polished the code up as much as I possibly can. I think my code for this looks fairly nice. #include [orange]stdio.h> #include [orange]stdlib.h> #include [orange]math.h> int main() { int x, y; int * a[] = {&x, &y}; printf("Integer 1: "); scanf("%d", &x); printf("Integer 2: "); scanf("%d", &y); int b = (*a[0]) * (*a[1]); printf("The multiple of %d & %d is %d.\n", x, y, b); return 0; } I actually feel satisfied with this. The only thing I think I can do now is push myself further. I want to learn how to make this program allow users to input various other functions; make it a real calculator. At least a basic one that can do Multiplication, Division, Subtraction && Addition. Ideally I would also like to make it permute floats and, or, whole numbers. Not one or the other. I figure this will take some understanding of how to use"if" statments though. I will have to watch more videos on C I figure and work here, haha. Oh, also, I tried to get my program to take the sum total of my array and square root it, but, It wouldn't let me square root the variable. GCC kept saying that sqrt is an undefined function, or, something. I don't even understand that because sqrt works fine on my other program.
(214.50 KB 297x361 f.png)
>>963 Sorry anon, please ignore my previous post, I lazily chimed in to the conversation and made some statements that were ill-informed. You can definitely do the scan function like you originally wanted... the first part of this post >>932 is how I would do it. I'm really embarrassed... I will read the whole discussion before responding next time...
>>970 Lol, it's ok anon. I was just really confused, LOL. I was watching a video on doing functions and for some reason gcc will not compile other functions if they come after main, so, I have to do all my functions BEFORE main which is weird, but, I figured it out: #include [orange]stdio.h> #include [orange]stdlib.h> #include [orange]math.h> void m() { int x, y; int * z[] = {&x, &y}; printf("Integer 1: "); scanf("%d", &x); printf("Integer 2: "); scanf("%d", &y); int a = (*z[0]) + (*z[1]); } void b() { int c, d; int * e[] = {&c, &d}; printf("Integer 1: "); scanf("%d", &d); printf("Integer 2: "); scanf("%d", &d); int f = (*e[0]) - (*e[1]); } void g() { int h, i; int * o[] = {&h, &i}; printf("Integer 1: "); scanf("%d", &h); printf("Integer 2: "); scanf("%d", &i); int j = (*o[0]) * (*o[1]); } void k() { int l, m; int * p[] = {&l, &m}; printf("Integer 1: "); scanf("%d", &l); printf("Integer 2: "); scanf("%d", &m); int n = (*p[0]) / (*p[1]); } int main() { char q[] = {+, -, *, /}; printf("What operation would you like? (+, -. *. /)"); scanf("%c"); if +; do m(); return 0; } It's not done, but, I am actually trying to make a calculator here. I have used if statements in a long ass time, or, do statments. The only real issue I am running into here is how to define +, *, -, / etc etc etc. it seems.
>>979 You can put just the function header before main and then define functions after main if you prefer it that way. eg. void m(); void b(); void g(); void k(); int main() { //Do something } void m() { //m definition } >The only real issue I am running into here is how to define +, *, -, / etc etc etc. it seems. Use switch case for that char c; //This is where you put user input switch(c) { case '+': //call function break; case '-': //call another function break; default: //Default happens if nothing else matches. Print some error message maybe break; }
>>980 I tried that and gcc still wouldn't compile it; I did what you said; I think I did it right. int main() { char c; scanf("%c", c); switch(c) { case '+': m(); break; case '-': b(); break; default: printf("Unacceptable entry"); break; } } The only issue I am having now: Newmethodsmath.c: In function ‘main’: Newmethodsmath.c:52:9: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘int’ [-Wformat=] scanf("%d", c);
>>980 Also, maybe you can explain switch, break & case to me better. Just so I have a better understanding of the, I've never used them before.
>>982 Scanf expects a pointer to a variable instead of a value, because if you pass a value you copy whatever there was before you called scanf, when you pass a pointer scanf will be able to insert a value to your variable. You can get a pointer of your variable by writing & before variable name. eg. scanf("%c", &c); will pass c as a pointer to scanf. >Also, maybe you can explain switch, break & case to me better Switch is used when you want to compare a variable against a predefined set of conditions. This structure shouldn't be used if there's only 2 conditions or less, because then if/else is a better choice. After case you enter the value you want your variable to be compared to. If it is equal, then it will start executing code after that statement until it finds a break keyword, then it exits the switch block. If it isn't equal, then it looks for another case statement, and if there are no more case statements, it goes to default. It is executed when no case matched, in your case it should print an invalid operation error, as it does in your example. You can use any numerical type with switch(and yes, in C char is a numerical type). Note that case and default end with a colon, instead of a semicolon.
>>985 I see, I see. Now gcc is telling me: Newmethodsmath.c: In function ‘main’: Newmethodsmath.c:63:5: error: expected ‘;’ before ‘case’ case '/': ^~~~
Post code before that case. I guess you forgot a semicolon
>>989 Lmfao, that was exactly it. I forgot the semi colon, LOL. It's working now. HOW EXCITING I JUST WROTE A CALCULATOR IN C :DDDDDD
>>963 >GCC kept saying that sqrt is an undefined function, or, something. Add -lm to linker flags. If you're not using a build system, then add it as a command line option somewhere after the name of your source code file. Eg. gcc example.c -o exename -lm
>>990 Correction, I fixed it but it is not with out bugs: #include [orange]stdio.h> #include [orange]stdlib.h> #include [orange]math.h> void m() { int x, y; int * z[] = {&x, &y}; printf("Integer 1: "); scanf("%d", &x); printf("Integer 2: "); scanf("%d", &y); int a = (*z[0]) + (*z[1]); printf("The sum of %d & %d is %d\n", x, y, a); } void b() { int c, d; int * e[] = {&c, &d}; printf("Integer 1: "); scanf("%d", &d); printf("Integer 2: "); scanf("%d", &d); int f = (*e[0]) - (*e[1]); printf("The sum of %d & %d is %d\n", c, d, f); } void g() { int h, i; int * o[] = {&h, &i}; printf("Integer 1: "); scanf("%d", &h); printf("Integer 2: "); scanf("%d", &i); int j = (*o[0]) * (*o[1]); printf("The sum of %d & %d is %d\n", h, i, j); } void k() { int l, m; int * p[] = {&l, &m}; printf("Integer 1: "); scanf("%d", &l); printf("Integer 2: "); scanf("%d", &m); int n = (*p[0]) / (*p[1]); printf("The sum of %d & %d is %d\n", l, m, n); } int main() { char c; printf("What function would you like: "); scanf("%c",&c); switch(c) { case '+': m(); break; case '-': b(); break; case '*': g(); case '/': k(); default: printf("Unacceptable entry. Try again.\n"); break; } return 0; } For some reason when I subtract something the first integer always comes out as 39655 or some variant of that. Everything else works fine but when I multply or divide it runs the script again and then prints the default switch statement. Example: What function would you like: * Integer 1: 5 Integer 2: 5 The sum of 5 & 5 is 25 Integer 1: ? Integer 2: The sum of 5 & 5 is 1 Unacceptable entry. Try again. Or What function would you like: / Integer 1: 90 Integer 2: 3 The sum of 90 & 3 is 30 Unacceptable entry. Try again. And subtraction is all fucked. What function would you like: - Integer 1: 1 Integer 2: 1 The sum of 32767 & 1 is 32766
Oh and ignore the fact everything says "Sum" I am just being lazy right now
>>995 You didn't add break after multiplication and division. Every case should be ended with a break, otherwise they just go over to other cases case '/': //do something break; //Without this, next case will be executed without break, division would execute another case, and another until one is actually terminated with break, then it would stop. >division You assign twice to d. Pass a pointer to c in one of scanf calls.
>>998 >>division I meant subtraction not division
>>999 check'd
>>1000 >1000 Check'd
>>999 Legit, yep, it's working now. Thanks for the tips!
C newb here again: So, I am trying to add square rooting into my functions for my calculator and I can't seem to figure out how to get sqrt() to square root my variables. Am I missing something here? void q() { double r; printf("What would you like to square? "); scanf("%lf", &r); sqrt(r); }
>>1006 Have you tried printing the result out?
>>1006 sqrt returns the result of square root. You could write something like r = sqrt(r);
>>1008 So something like this? void q() { double r = sqrt(r); printf("What would you like to square? "); scanf("%lf", &r); } This is returning: /tmp/ccnr1MzI.o: In function `q': Newmethodsmath.c:(.text+0x31d): undefined reference to `sqrt' collect2: error: ld returned 1 exit status >>1007 Well we have to get the result first before I can actually print it out, lol.
(49.37 KB 1100x619 n3sybjq_orig.jpg)
>>1009 I mean like this: void q() { double r; printf("What would you like to square root? "); scanf("%lf", &r); printf("Result is: %lf\n", sqrt(r)); } As for the linker error, you need to link the math library with "-lm". For example: gcc -lm source.c -o program Where "source.c" is your source file and "program" will be the name of your executable. Modify as you see fit.
>>1007 It's still giving me the same compile error.
>>1011 Post the command that you are using to compile it.
>>1011 Put -lm at the end. Eg. gcc example.c -o test -lm
>>1013 Lmao, well, that worked and it compiled fine, but, now there is a bug in the sqrt function. What function would you like: s What would you like to square? 40 The square root of 40 is 147.912136. That's what it keeps spitting out. void q() { int s; double r = sqrt(s); printf("What would you like to square? "); scanf("%d", &s); printf("The square root of %d is %lf.\n", s, r); } ^The function for reference.
>>1014 It's in the wrong order. You need to read in the user input BEFORE you use it. int s; double r; printf("What would you like to square? "); scanf("%d", &s); r = sqrt(s); printf("The square root of %d is %lf.\n", s, r); The semi-colons separate statements that are executed sequentially. What I have written will be executed thus: 1. A variable s with the type int is declared. Since there is no assignment, its value will be undefined, meaning it can be anything and it is unsafe to use. 2. A variable r with the type double is declared. Its value is undefined. 3. You print a message. 4. An int value will be read into the variable s. From now one, the value of s will be the user provided input. (if the input was in the correct format, etc.) 5. The value of r is set to the result of the expression "sqrt(s)". 6. A message containing the value of s and r is printed out. Try writing a same step-by-step execution for your code. Can you see what the problem is?
>>1015 Yes, no, I see what is wrong I just don't see how I guess nesting the sqrt type inside the r variable wouldn't achieve the same effect. Hmm, I guess, yeah, now that I think about it though if the program is reading it like that I guess it has no way of knowing that s is defined by the scan. But, doesn't a point tell it what the value of s is in the first place?
>>1016 You are not giving the computer a system of equations to solve, but commands to execute sequentially. When you say "r = sqrt(s)" it means to evaluate sqrt(s) and assign its result to r. You cannot store the expression in the variable.
>You need to read in the user input BEFORE you use it. This a fabulous thread. Please continue.
(241.98 KB 563x564 1585233814942.png)
C fag here, What should I build today? I was thinking of building a digital clock, but, I wouldn't know where to start with that.
>>1025 I was also thinking of adding the ability to work with floats on my calculator, but, I think that is, currently, above my paygrade. How would I even go about doing something like that? I was thinking maybe if/else statements in my switch function, though, I still don't totally get how they work or their applicability.
>>1025 These functions have what you need: https://www.cplusplus.com/reference/ctime/time/ https://www.cplusplus.com/reference/ctime/localtime/ https://www.cplusplus.com/reference/ctime/strftime/ First, you should call time(NULL) to get the current time, then pass that to localtime to get a tm structure, which you then pass to strftime. Strftime works kind of like sprintf, but the syntax is a little bit different, it's described in the third link I've given you.
>>1026 Do you mean float inputs or float outputs? If you mean inputs, then you should just change the scanf format, change variable types and it should work seamlessly.
>>1028 Well I want it so that my calculator can take floats &&, or, integers and spit out floats and or integers. I want the user to have the choice. Like a real calculator.
>>1028 Also, what other functions can I add to my calculator? I added the ability to put numbers to the power of, and square rooting already.
>>1029 Just use floats, you can do the same math with them as with integers, but they support fractions.
>>1031 Yeah but the output will still be a float even if there is no value behind them. For example: 25 / 5 is 5 but with a float it will be 5.00000. I want it to out 5 if necessary. Maybe celi and if statements?
>>1032 Use %g when printing the output and it should skip unnecessary zeros.
>>1030 How about sequences? Getting the Nth Fibonacci number? Factorials? Digits of Pi? Prime numbers? The choices are endless.
>>1034 I like the idea of adding Digits of Pi into the equation. Factorials would be nice too, but, wouldn't that require data-basing every factor of a given number? I mean, I have done that before, but, is there an easier way?
>>1036 Factorials can be easily done with a for loop. int factorial = 1; for(int i = 2; i [orange]= userinput; ++i) { factorial *= i; }
>>1037 what the fuck is <?
For some reason, bunkerchan filters < sign to [orange] in code tags.
>>1042 Lmao what
>>1051 <Orange
ok so I updated my code: #include [orange]stdio.h> #include [orange]stdlib.h> #include [orange]math.h> void m(), b(), g(), k(), q(), u(); int main() { char c; printf("What function would you like: "); scanf("%c",&c); switch(c) { case '+': m(); break; case '-': b(); break; case '*': g(); break; case '/': k(); break; case 'p': q(); break; case 's': u(); break; default: printf("Unacceptable entry. Try again.\n"); break; } return 0; } /*Addition*/ void m() { int x, y; int * z[] = {&x, &y}; printf("Integer 1: "); scanf("%d", &x); printf("Integer 2: "); scanf("%d", &y); int a = (*z[0]) + (*z[1]); printf("The sum of %d & %d is %g\n", x, y, a); } /*Subtraction*/ void b() { int c, d; int * e[] = {&c, &d}; printf("Integer 1: "); scanf("%d", &c); printf("Integer 2: "); scanf("%d", &d); int f = (*e[0]) - (*e[1]); printf("The sum of %d & %d is %g\n", c, d, f); } /*Multiplication*/ void g() { int h, i; int * o[] = {&h, &i}; printf("Integer 1: "); scanf("%d", &h); printf("Integer 2: "); scanf("%d", &i); int j = (*o[0]) * (*o[1]); printf("The sum of %d & %d is %g\n", h, i, j); } /*Division*/ void k() { int l, m; int * p[] = {&l, &m}; printf("Integer 1: "); scanf("%d", &l); printf("Integer 2: "); scanf("%d", &m); int n = (*p[0]) / (*p[1]); printf("The sum of %d & %d is %g\n", l, m, n); } /*Power of*/ void q() { int s; int t; int r; printf("Input your integer: "); scanf("%d", &s); printf("Now input power of: "); scanf("%d", &t); r = pow(s, t); printf("%d to the power of %d is %g.\n", s, t, r); } /*Square Root*/ void u() { int v; double w; printf("What would you like to square: "); scanf("%d", &v); w = sqrt(v); printf("The square root of %d is %g\n", v, w); } I was trying to take the advice of >>1033 but for some reason gcc keeps spitting out: Newmethodsmath.c: In function ‘m’: Newmethodsmath.c:49:32: warning: format ‘%g’ expects argument of type ‘double’, but argument 4 has type ‘int’ [-Wformat=] printf("The sum of %d & %d is %g\n", x, y, a); ~^ %d Newmethodsmath.c: In function ‘b’: Newmethodsmath.c:62:32: warning: format ‘%g’ expects argument of type ‘double’, but argument 4 has type ‘int’ [-Wformat=] printf("The sum of %d & %d is %g\n", c, d, f); ~^ %d Newmethodsmath.c: In function ‘g’: Newmethodsmath.c:76:32: warning: format ‘%g’ expects argument of type ‘double’, but argument 4 has type ‘int’ [-Wformat=] printf("The sum of %d & %d is %g\n", h, i, j); ~^ %d Newmethodsmath.c: In function ‘k’: Newmethodsmath.c:89:32: warning: format ‘%g’ expects argument of type ‘double’, but argument 4 has type ‘int’ [-Wformat=] printf("The sum of %d & %d is %g\n", l, m, n); ~^ %d Newmethodsmath.c: In function ‘q’: Newmethodsmath.c:103:37: warning: format ‘%g’ expects argument of type ‘double’, but argument 4 has type ‘int’ [-Wformat=] printf("%d to the power of %d is %g.\n", s, t, r); ~^ %d Any ideas on what I am doing wrong? Should it recognize the difference between the floats an ints? What is %g?
>>1054 Lol, Scratch that. I actually figured it out on my own. Be proud of me /tech/. I figured out that I needed to replace the int statements with double statements and it appears to be working fine and doing exactly what I want. :^) Though, I still can't figure out how to get the output of the variables for what the function is working on to not come out only as floats. For example: When I add 5 + 5 for 10; 10 comes out as an integer, but, when the printf statements prints off 5 and 5 they still come out as 5.000000 not 5. For some reason gcc was yelling at me about altering my %f statements to %g statements
>>1057 >5 + 5 for 10; 10 comes out as an integer, but, when the printf statements prints off 5 and 5 they still come out as 5.000000 not 5. I don't really know what you're trying to do here, but you scanf those numbers as integers, and also print them as integers, so they shouldn't have any fractions in them. You should use %g in both scanf and printf, and change their type to double.
The feature you should add from real calculators is the ability to chain computations by reusing the result of the previous computation as an argument for the next computation. -> + -> 5 -> 5 10 -> * -> r -> 2 20 Then you should implement cos in the same way as sqrt. Then you should start with 0, apply cos and keep applying it to the previous result. At this point you will see magic happen.
>>1063 What is cos? How would I go about doing something like that? Loops?
>>1069 >What is cos? The cosine function. Lives with sqrt. https://en.cppreference.com/w/c/numeric/math/cos >How would I go about doing something like that? Loops? Yes. Store the result between computations so it is available for reuse and use whichever loop you like. https://en.cppreference.com/w/c/language/while
>>1074 >Yes. Store the result between computations so it is available for reuse and use whichever loop you like. What should I use to store the result?
>>1076 As you only need the last result, a single variable will do.
>>1077 This is the code I have so far for the loop: /*Addition*/ void m() { char Y, N; double a; double xx, yy; double * z[] = a + {&xx, &yy}; printf("Integer 1: "); scanf("%lf", &xx); printf("Integer 2: "); scanf("%lf", &yy); a = (*z[0]) + (*z[1]); printf("The sum of %g & %g is %g\n", xx, yy, a); printf("Would you like to continue? Yes/no: "); scanf("%c", Y, N); if(Y){ main();} else{ printf("goodbye!"); } } I decided to go with an if statement since we only have two options Y/N. But, for some reason, gcc keeps demanding that %c is not a char but an int: Newmethodsmath.c:52:9: warning: format ‘%c’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] scanf("%c", Y, N); ~^ Newmethodsmath.c:52:7: warning: too many arguments for format [-Wformat-extra-args] scanf("%c", Y, N); ^~~~ I don't get it. Also, Isn't the value of already stored in the double A in my program? Wouldn't the program just be calling that?
>>1084 I need a way to make z = a + the value of xx and yy. Is the default value of a variable 0?
>>1085 Scratch that I figured out I could actually assign the value of a to itself, so insted off [code] a = (*z[0]) + (*z[1]); I can do [code] a = (*z[0]) + (*z[1]) + (a);
>>1086 You could've as well written a += (*z[0]) + (*z[1]) It's a shorter way of setting a to itself + some other number.
>>1085 >Is the default value of a variable 0? No. You must initialize variables before using their value, otherwise they contain random nonsense. Also, since you are the proverbial >being this new you should add -pedantic to your gcc invocation and fix every warning.
>>1090 Pedantic doesn't appear to be giving me anymore information for why it wont compile my program right now. Is %c not a character or something?
>>1092 The -pedantic option will, among other things, point out uninitialized use of variables. >Is %c not a character or something? >char Y, N; >scanf("%c", Y, N); You need to pass a pointer to char, not a value of char, and not two of them. char yorn; scanf("%c", &yorn);
>>1094 Yeah, lol. I figured that out. Now it will compile, but, the if statement is giving me bugs. Uh, also, how do I make a choice between yes and no then if I can only declare one variable to scanf?
>>1095 You use an 'if' test on yorn. https://en.cppreference.com/w/c/language/if The equality test is ==. The relevant char literals are 'y' and 'n'.
So As it turns out there was an error, actually, with c itself. https://stackoverflow.com/questions/8464620/program-doesnt-wait-for-user-input-with-scanfc-yn Apparently this was keeping my scanf type from functioning properly. I ended up fixing it and now the if type is working; I can return back to the main function. The only issue is now the program is not adding variables back on top of a that should be stored. Apparently they get destroyed after every return to main. Now that's the issue I am having.
>>1099 >if(Y){main();} The main function is not appropriate for this type of looping via recursion. The previous result is not passed into the next invocation so this information is lost. Either use a looping construct >>1074 or move what is currently in main to a function that takes the previous result as a parameter. I. int keepgoing = 1; while (keepgoing) { // ask for function switch(c){ ... } // ask for continuation // if 'n' set keepgoing to 0 } II. int frobnicate (int previousresult) { // the stuff that was in main // if continuation answer is 'y' return frobnicate (newresult); } int main(){ frobnicate(0); return 0; }
double frobnicate (double previousresult) {
(143.72 KB 1024x762 1585314025155.jpg)
>>1113 I just ended up setting up something like this: 1 #include [orange]stdio.h> 2 #include [orange]stdlib.h> 3 #include [orange]math.h> 4 5 void m(), b(), g(), k(), q(), u(); 6 double a, n, j, f; 7 int main() 8 { 9 char c; 10 printf("What function would you like: "); 11 scanf(" %c",&c); 12 fflush(stdout); 13 switch(c) 14 { 15 case '+': 16 m(); 17 break; 18 case '-': 19 b(); 20 break; 21 case '*': 22 g(); 23 break; 24 case '/': 25 k(); 26 break; 27 case 'p': 28 q(); 29 break; 30 case 's': 31 u(); 32 break; 33 default: 34 printf("Unacceptable entry. Try again.\n"); 35 break; 36 } 37 return 0; 38 } 39 40 /*Addition*/ 41 void m() 42 { 43 char y; 44 double xx, yy; 45 double * z[] = {&xx, &yy}; 46 printf("Inteuer 1: "); 47 scanf("%lf", &xx); 48 printf("Integer 2: "); 49 scanf("%lf", &yy); 50 a = (*z[0]) + (*z[1]) + (a); 51 printf("The sum of %g & %g is %g\n", xx, yy, a); 52 printf("Would you like to continue? Y/N: "); 53 scanf(" %c",&y); 54 if( y == 'y'){ 55 main();} 56 else{ 57 printf("Goodbye!\n"); 58 } 59 60 } As you can tell the if statment returns to main if the condition of y being 'y' is true and for all else it fails. It could probably be nicer, but it works for now. What I really need is a way to make the program stop if 'N' is entered and use else to reprint line 52. Also, multiplication and division are giving me quite a bit of trouble with recursiveness; [code] 84 /*Multiplication*/ 85 void g() 86 { 87 char y; 88 double h, i; 89 double * o[] = {&h, &i}; 90 printf("Integer 1: "); 91 scanf("%lf", &h); 92 printf("Integer 2: "); 93 scanf("%lf", &i); 94 j = (*o[0]) * (*o[1]) * (j); 95 printf("The sum of %g & %g is %g\n", h, i, j); 96 printf("Would you like to continue? Y/N: "); 97 scanf(" %c",&y); 98 if( y == 'y'){ 99 main();} 100 else{ 101 printf("Goodbye!\n"); 102 } The issue I am running into with multiplication and division is, I believe, the default value for a variable on my machine is 0, or, something because the inclusion of J, for example, being nested inside of itself is result in an out put of 5 x 5 = 0. The only way I could get that output is if the default value of a variable was 0. How do I get around this??
>>1121 The value of uninitialized variable depends on many factors, it could be 0, or it could be close to MAX_INT or something. This can also be compiler dependent, you should always initialize variables before using them. If you want, you can set j to be 1. double a, n, f; double j = 1; >What I really need is a way to make the program stop if 'N' is entered and use else to reprint Use else if in a loop for that. while(true) { char y; scanf("%c",&y); y = tolower(y); //Convert to lower case so comparing will be case-insensitive if(y == 'y') { return; //Return to main } else if(y == 'n') { //Printf something exit(0); //Immediately exit the program with status code 0 } else { printf("Unrecognized input!"); continue; //Continue this loop until user inputs valid data } } If tolower gives you errors include ctype.h Also you should add a loop to your main function so user can choose something else again.
>>1121 If you put the continuation question after the switch, you no longer have to put it into every subfunction. >I just ended up setting up something like this This was already your call pattern in >>1084. Use I or II from >>1113. >What I really need is a way to make the program stop if 'N' is entered and use else to reprint line 52. For that you need a loop >>1074 int answered = 0; while (!answered) { // print question // scan answer switch (y) { case 'y': answered = 1; // action for yes break; case 'n': answered = 1; // action for no break; default: // nothing break; } } >I believe, the default value for a variable on my machine is 0 >The only way I could get that output is if the default value of a variable was 0. Answer is in >>1090 >How do I get around this?? You set the stored result to the result of the operation. j = (*o[0]) * (*o[1]); You only reuse the previous result as one of the operands if the user requests it >>1063 ... 10 -> * -> r -> 2 20 Also, drop the 'o' array entirely and use result = h * i; like a sane person.
>>1127 Well, I updated my code to include recursion on variables so that second passes include the value of the variable on the first pass. I also added the option of whether or not the user, actually, wants to do this or not; They can choose. I also took the loop out of each function and just added the loop to its own function itself that each subsequent function calls. Sorry in advance to anyone reading this, I didn't understand how hard it would be to read something like this using names for my variables like X, Y and Z. 1 #include [orange]stdio.h> 2 #include [orange]stdlib.h> 3 #include [orange]math.h> 4 #include [orange]ctype.h> 5 6 void m(), b(), g(), k(), q(), u(); 7 double a, n, j, f = 0; 8 char y, nn; 9 int main() 10 { 11 char c; 12 printf("What function would you like: "); 13 scanf(" %c",&c); 14 fflush(stdout); 15 switch(c) 16 { 17 case '+': 18 m(); 19 break; 20 case '-': 21 b(); 22 break; 23 case '*': 24 g(); 25 break; 26 case '/': 27 k(); 28 break; 29 case 'p': 30 q(); 31 break; 32 case 's': 33 u(); 34 break; 35 default: 36 printf("Unacceptable entry. Try again.\n"); 37 main(); 38 break; 39 } 40 return 0; 41 } 42 /* loop */ 43 void loop() 44 { 45 printf("Would you like to continue? Y/N: "); 46 scanf(" %c",&y); 47 y = tolower(y); 48 if( y == 'y'){ 49 printf("Would you like to retain the value of the last pass? Y/N: "); 50 scanf(" %c", &nn); 51 if( nn == 'n'){ 52 j = 0; 53 n = 0; 54 main();} 55 else if( nn = 'y'){ 56 main();} 57 else{ 58 loop(); 59 }} 60 else if( y == 'n'){ 61 n = tolower(n); 62 printf("Goodbye!\n"); 63 exit(0);} 64 else{ 65 loop(); 66 67 } 68 } 69 70 /*Addition*/ 71 void m() 72 { 73 char y; 74 double xx, yy; 75 double * z[] = {&xx, &yy}; 76 printf("Inteuer 1: "); 77 scanf("%lf", &xx); 78 printf("Integer 2: "); 79 scanf("%lf", &yy); 80 a = (*z[0]) + (*z[1]) + (a); 81 printf("The sum of %g & %g is %g\n", xx, yy, a); 82 loop(); 83 84 } 85 86 /*Subtraction*/ 87 void b() 88 { 89 char y; 90 double c, d; 91 double * e[] = {&c, &d}; 92 printf("Integer 1: "); 93 scanf("%lf", &c); 94 printf("Integer 2: "); 95 scanf("%lf", &d); 96 f = (*e[0]) - (*e[1]) - (f); 97 printf("The sum of %g & %g is %g\n", c, d, f); 98 loop(); 99 100 } 101 102 /*Multiplication*/ 103 void g() 104 { 105 char y, n; 106 double h, i; 107 double * o[] = {&h, &i}; 108 printf("Integer 1: "); 109 scanf("%lf", &h); 110 printf("Integer 2: "); 111 scanf("%lf", &i); 112 j = (*o[0]) * (*o[1]) * (j!=0?j:1); 113 printf("The sum of %g & %g is %g\n", h, i, j); 114 loop(); 115 116 } 117 118 /*Division*/ 119 void k() 120 { 121 char y; 122 double l, m; 123 double * p[] = {&l, &m}; 124 printf("Integer 1: "); 125 scanf("%lf", &l); 126 printf("Integer 2: "); 127 scanf("%lf", &m); 128 n = (*p[0]) / (*p[1]) / (n!=0?n:1); 129 printf("The sum of %g & %g is %g\n", l, m, n); 130 loop(); 131 132 } 133 134 135 /*Power of*/ 136 void q() 137 { 138 char y; 139 double s; 140 double t; 141 double r; 142 printf("Input your integer: "); 143 scanf("%lf", &s); 144 printf("Now input power of: "); 145 scanf("%lf", &t); 146 r = pow(s, t); 147 printf("%g to the power of %g is %g.\n", s, t, r); 148 loop(); 149 150 } 151 152 /*Square Root*/ 153 void u() 154 { 155 char y; 156 double v; 157 double w; 158 printf("What would you like to square: "); 159 scanf("%lf", &v); 160 w = sqrt(v); 161 printf("The square root of %g is %g\n", v, w); 162 loop(); 163 164 } I'm pretty satisfied with it. Now I am just thinking of what to add. Kind of want to try and integrate pi into it, or, the fabbanaci like that one anon suggested. What could I do to make my code less messy and more readable to the outside user?
>>1142 >What could I do to make my code less messy and more readable to the outside user? Stop using single letter names for functions and variables, and stop calling main explicitly in your code. You're supposed to return to main, not call it again. Also stop using fixed-length arrays for storing data that can be as well stored in two different variables. If your IDE/editor(I'm assuming you're not writing it all in notepad) tells you about unused variables, then delete them. You don't have to create a char variable in every function if you're not gonna use it. And start using loops ffs, recursive calls should be avoided as much as possible. You also should avoid global variables, because any function you call could fuck them up, which makes it extremely easy for bugs to happen. If I were you, that's how I would've written your program: #include [orange]stdio.h> #include [orange]stdlib.h> #include [orange]stdbool.h> #include [orange]math.h> #include [orange]ctype.h> #include [orange]string.h> #define INFO_RETAINED "INFO: Using retained number from previous operation\n" typedef enum _BasicOperation { Addition = '+', Subtraction = '-', Division = '/', Multiplication = '*' } BasicOperation; bool yesNoQuestion(const char*); double readNumber(); double genericOperation(BasicOperation, double); double powerOf(double); double squareRoot(double); int main() { char c; double retained = 0; while(true) { printf("What function would you like: "); scanf(" %c",&c); fflush(stdin); c = tolower(c); switch(c) { case '+': case '-': case '*': case '/': retained = genericOperation((BasicOperation)c, retained); break; case 'p': retained = powerOf(retained); break; case 's': retained = squareRoot(retained); break; default: printf("Unacceptable entry. Try again.\n"); continue; } if(yesNoQuestion("Would you like to continue?")) { if(!yesNoQuestion("Would you like to retain the value of the last pass?")) retained = 0; } else { printf("Goodbye!\n"); return 0; //Instead of exit(0) cause it's the main function } } return 0; } bool yesNoQuestion(const char* msg) { char c; while(true) { printf("%s Y/N: ", msg); fflush(stdin); scanf(" %c", &c); switch(tolower(c)) { case 'y': return true; case 'n': return false; default: printf("ERROR: Invalid input\n"); fflush(stdin); continue; } } } double readNumber(const char* msg) { double ret; while(true) { printf("%s: ", msg); if(scanf(" %lf", &ret) != 1) { printf("ERROR: Invalid input.\n"); fflush(stdin); continue; } return ret; } } //Basic mathematical operations double genericOperation(BasicOperation op, double retained) { double num1, num2, ret = 0; if(retained != 0) { num1 = retained; printf(INFO_RETAINED); } else { num1 = readNumber("Integer 1"); } num2 = readNumber("Integer 2"); switch(op) { case Addition: ret = num1 + num2; break; case Subtraction: ret = num1 - num2; break; case Multiplication: ret = num1 * num2; break; case Division: ret = num1 / num2; break; } printf("The sum of %g & %g is %g\n", num1, num2, ret); return ret; } double powerOf(double retained) { double num, power, ret = 0; if(retained != 0) { num = retained; printf(INFO_RETAINED); } else { num = readNumber("Input your integer"); } power = readNumber("To the power of"); ret = pow(num, power); printf("%g to the power of %g is %g.\n", num, power, ret); return ret; } double squareRoot(double retained) { double num, ret = 0; if(retained != 0) { num = retained; printf(INFO_RETAINED); } else { num = readNumber("What would you like to take square root of?"); } ret = sqrt(num); printf("The square root of %g is %g\n", num, ret); return ret; }
(1.44 MB 1116x1280 loop.png)
Anon needs to learn loops.
(823.61 KB 424x600 1342098188722_29543653.png)
>>1189 Anon needs to read a book.
>>1192 There's a lot of shit you simply aren't going to learn from books and only understand from being taught/first hand experience.
(439.40 KB 1349x1500 1586907648129.jpg)
>>1198 That's why good books have carefully chosen exercises. You really don't need anything else.
>>1200 Oh??? What books would you recommend senpai?
>>1204 SICP
(3.63 MB 3800x2534 worksafe.png)
Anon needs to go through SICP.
>>1204 For C, K&R is the gold standard.
>>1218 Books like this for python?
>>1221 Check out the official python docs. https://docs.python.org/3.8/ Also i think that "Automate the Boring stuff with Python" is good, although i never read it.
(1.19 MB ctut.pdf)
>>1218 For a beginner, K&R sucks. They go over too many things without fully explaining the situation. After page 100 you'll have to go back to fully understand anything further. I had a better experience with gnuctut because it goes in good detail and torfs because it explains every step and all code written and doesn't cut corners (despite being quit short). https://cprog.tomsweb.net/
Has anyone read: The GNU programming tutorial? It's a damn good read.
Did anon give up on C?
>>1511 Nah, i;m going through some shit, personally. I haven't been able to focus on it. Fuckiong, land lord being a cunt, roomies leaving and dropping everything on me. Just a lot of shit man. It's nearing the day my mom died. I have just been unable to really focus on my programming, tbh. I am having an issue, though. I'll post about it later before bed. Maybe you guys can help me figure it out. For some reason I can't get the loop to function properly; Basically, with the help of my buddy, we made the cal work so that the user can choose wether they would like to retain the value of the last pass or not, but, for some reason, the loop refuses to accept Y/N and just defaults to the else statement. It's odd.
A bit off-topic but should I go for CIS or CS? I'm not afraid of math btw, just coming out of an unsuccessful run at engineering.
>>1541 Tbhe fuck is CIS?
(108.25 KB 960x540 cb.jpg)
>>1548 Creamy Incestuous Sisters
>>1541 CS degree is more prestigious, it's always the better option even if you hate math.
Nothing right now anon. I should be working on my programming studies but the corona thing has fucked up my routine of studying. >>1548 Confederacy of Independent Systems
Does anyone know some good books on C?
>>1563 Thanks!
>>1566 just be cautious that many major open source projects and embedded systems still don't support C99, C11, or C17 features
>>1554 >CS degree is more prestigious Really? Interesting. My uni offers both courses and the classes are fully interchangeable.
>>1567 What is >C99, C11, C17
>>1578 Various versions of the C language standard. The number indicates the year the standard was published.
Any anons here know x86-64 assembly?
>>1759 No but I have this
>>1759 I can read it but never wrote much in it.
>>1759 I got an A in my assembly class this semester... I know it's only a noob class using MIPS but maybe I can help. what do you want to know?
(1.48 MB 540x378 dragonmaidthumbsup.gif)
>>1785 Congratulations!
>>1785 Currently learning x86-64(i know it's very big and not really a good starting assembly lang) i want to know if there are some good books or resources specific on x86-64. I am reading Seyfarth's Introduction to 64 Bit Intel Assembly Language Programming for Linux book and i had read a little bit of Jo Van Hoey's Beginning x64 Assembly Programming.
I started learning shell scripting, and man I fucking love the syntax, it is so fucking good to program in it
>>1807 Even the ugly ifs and the weird stderr to stdout operator?
>>1807 I can recommend "Classic Shell Scripting", it is a great book on the topic. Although it is concerned with the POSIX shell, for modernities you will still have to skim the bash manual. I especially loved the chapter on awk, the program presented there is a bit of an overkill, but knowing the basics of awk has been invaluable for shell scripting. Oh, and be sure to install shellcheck and set it up for flycheck. >>1808 There are tons of historical mistakes and weird behaviour in POSIX sh and bash but those two things are actually completely understandable and well specified.
I'm working on a proxy server. Something like mitmproxy, but scriptable with lua. Currently scripts can modify html and javascript data on the fly. I use it to bypass anti-adblockers and such. Though I should work on the script documentation, and possibly remodel scripting. Currently, every script contains a lua table with the name "plugin", and in this table are all the script information, such as on what hostnames will it work on, the type of data to modify, the function that actually modifies the data etc. It looks now kind of like this: plugin = { host = "*example.com", --wildcards are supported in the hostname and paths paths = { "/js/main.js", "/js/antiadblock.js" }, response = function(js, http) --js contains the javascript response text, after minification. js.NopFunction("onAdblockDetected") --It's an object, and it contains methods for clearing a function's body, js.SetFunction("detectAdblock", "return false;") --setting a function's body to some string and js.removeEventListener("keydown") --removing addEventListener and similar calls. --Http contains data such as the request uri, headers, http method etc. end } I don't know whether it should stay like this or should I rework it. Maybe use global variables instead of a plugin table? I should also create some way of sharing scripts when I release it, and add a way for a script to redirect connections.
>>1808 It is one of my favorite parts about it, don't know why but I really like how it looks
>>1805 Mostly security, learning computer internals, reverse engineering, also i really like the language. >>1810 Just a heads up, if you plan to release the code you're working on you should rewrite the part that you posted here, because it can get you doxed.
>>1817 I've seen in a comment in an anti-adblocker code that removing the code is breaking dmca somehow, so I won't be releasing it under my name anyway. I don't want any feds near my house.
>>1821 I will release it through tor and under a nickname though, then it won't really matter if I post here or not.
>>1821 We are already watching your house.
>>1817 Just do crackmes fam, the other topics will naturally fall in place. You won't even have to study assembly on its own.
>>1807 It's great if you only have to combine a couple of commands, much simpler than in other languages. Once you have to manipulate complex data structures it can become very frustrating though, if not impossible (some devices only support sh and not bash).
>>1853 It's Turing complete.
Help me brothers I'm considering using scheme or haskell for my next project instead of COMMON LISP
>>1869 Sure, and asm is also turing complete, but you will never use it to replace your shell scripts. Now imagine having to work with convoluted json data in bash.
>>2940 https://stedolan.github.io/jq/ It's actually pretty convenient.
>>17 Working making changes to some Vue codebase. I kinda wanna die, ngl.
>>2939 Which one did you end up using?
>>17 Funnily enough, I'm currently working through SICP, CLRS and that one book by Patterson and Hennessy. Don't know if I'm just memeing myself or if this actually werks, but these books are pretty good so far.

Delete
Report

no cookies?