Always I am indebted.
Ruby was able to output as expected, but it doesn't work out as expected in C language.
Created in Ruby and C language.
I am attaching it as follows, so please check it.
-------------------------
■Problems
setup ia...Insert the value a into the variable i (i=1,2)
addition a... Calculate the value +a of variable 1 and substitute the calculation result to variable 2
subtract a... Calculate the value of variable 1 -a and substitute the calculation result to variable 2
■Example Input
4
setup120
setup240
addition40
subtract-20
■Expected output example
20
40
-----------------------------------------------------------------------------------------------
Ruby
t=gets.to_i
a = 0,0
US>t.times{
aary=gets.chomp.split('')
ifary[0] == "setup"
s=ary[1].to_i
n=ary[2].to_i
a[s-1] = n
elsifary[0] == "addition"
x =ary[1].to_i
a[1] = a[0] + x
elsifary[0] == "subtract"
y=ary[1].to_i
a[1] = a[0]-y
end
}
puts a.join('')
C
#include<stdio.h>
# include <string.h>
int main(void){
charary [3];
inta[2];
chat;
scanf("%s", & t);
for(int j=0;j<t;j++){
if(strcmp(t, "setup")==0){
ints=ary[1];
int n =ary[2];
n = a[s-1];
}
else if(strcmp(t, "addition")==0){
intx =ary[1];
a[1] = (a[0]+x);
}
else if(strcmp(t, "subtract")==0){
inty=ary[1];
a[1] = (a[0]-y);
}
}
printf("%d\n", a);
return 0;
}
It's not an answer, but it's too long to write in the comment section, so I'll use the answer section.
The big mistake is 3 points.
c does not actually have a string type (c to handle strings.Present c source is misleading and needs to be corrected as if the "pointer to char
" type is a string (array and pointer can be used in the same way, but completely different).The size of the array is determined at the time of array definition, or rather, it is a specification that must be determined, so it is not easy to "read any length of string" (the number of characters dynamically changes at the time of execution).Therefore, you can only read a string of up to N
characters (or use dynamic memory to handle arbitrary length strings).
Furthermore, when , it is good to be string literal, but the value of the expression is converted to "right side value of the pointer to first character."therefore, ==
cannot match strings.The pointer to the first character in the char
array that reads the user input and the pointer to the first character in the string literal "setup"
will never match, so use the function strcmp()
where Also, ary
has no part to load the string.
If you correct the above three points, it will work, but the quantity will be completely rewritten.Oira can write down the source code after rewriting, but since it's a great exercise, please read what Oira pointed out, correct it, and answer yourself. Self-answer is very welcome in SO.
So if you don't understand what Oira pointed out, you might want to buy an introductory book.
© 2024 OneMinuteCode. All rights reserved.