C program shows no error but doesn't show output - c

Roy wants to change his profile picture on Facebook. Now Facebook has some restriction over the dimension of picture that we can upload.
Minimum dimension of the picture can be L x L, where L is the length of the side of square.
Now Roy has N photos of various dimensions.
Dimension of a photo is denoted as W x H
where W - width of the photo and H - Height of the photo
When any photo is uploaded following events may occur:
If any of the width or height is less than L, user is prompted to upload another one. Print "UPLOAD ANOTHER" in this case.
If width and height are both large enough and
(a) if the photo is already square then it is accepted. Print "ACCEPTED" in this case.
(b) else user is prompted to crop it. Print "CROP IT" in this case.
Code:
#include <stdio.h>
#include <stdlib.h>
int main (void)
{
int len; /* len is the length of the side of square */
scanf("%d",&len);
int test;
scanf("%d",&test);
while(test--)
{
int w,h;
/* w - width of the photo and h- Height of the photo */
scanf("%d %d",&w,&h);
if(w==len && h==len)
{
printf("ACCEPTED\n");
}
else if(w>len || w==len && h>len || h==len)
{
printf("CROP IT\n");
}
else
{
printf("UPLOAD ANOTHER\n");/* print */
}
}
return 0;/* success */
}

If your problem is that you're seeing no output at all, it's likely because it's running in an IDE and the output window is closing before you can see it. Judicious use of a getchar() at the end of main() may be all you need to fix this, though I'd probably prefer to just run it from the command line.
In any case, since && has a higher precedence than ||, your second condition is effectively:
else if ((w > len) || (w == len && h > len) || (h == len))
which is clearly wrong since having a photo with width more than what was necessary would result in a request for cropping regardless of the other sub-conditions.
You would be better off following the textual specs more closely so that you can actually check it more easily. That would entail something like (with slightly simplified specs still meeting the original intent):
If any of the width or height is less than L, user is prompted to upload another one.
Otherwise both are large enough. If the photo is already square then it is accepted.
Otherwise user is prompted to crop it.
The code for that is a much simpler:
if ((w < len) || (h < len)) {
puts ("UPLOAD ANOTHER");
} else if (h == w) { // Both large enough otherwise previous
puts ("ACCEPTED"); // condition would have been true.
} else {
puts ("CROP IT");
}

Due to operator precedence,
else if(w>len || w==len && h>len || h==len)
is equivalent to:
else if(w>len || (w==len && h>len) || h==len)
What you need to use is:
else if( (w>len || w==len) && (h>len || h==len) && (w == h) )
You can simplify that to:
else if( w >= len && h >= len && w == h )
which can be further simplified to:
else if( w >= len && w == h )

It will show output but the program runs faster than you expect. It will close as soon as the output is displayed . It will not wait till you read it.
So use getch(); declared in conio.h to get a single key press as input after you have printed all the output (right before the return statement. It will make the program wait for the user to press a key before exiting.

here is the screenshot. it is running without error on me.
NOTE: This is not an answer. But this is just the only way to give picture example :) no need to up
Maybe you only need to put getchar(); at the end of the code before return to let the screen to pause for a while. it is just exiting very fast

Related

curses move backwards accounting for previous lines

Is there any way to move the cursor backwards while accounting for previous lines, i.e. when the cursor goes back from the beginning of the line it goes to the last non-empty character of the previous line?
So there's no built in method for this, so I had to write my own
void backspace(){
int x,y;
getyx(stdscr,y,x);
if(x == 0) {
if( y == 0 ) {
return;
}
x = getmaxx(stdscr) - 1;
move(--y,x);
char ch = ' ';
while(ch == ' ' && x != 0){
move(y,--x);
ch=inch();
}
} else {
move(y,x-1);
}
delch();
}
Note that I have removed some irrelevant file I/O related code that was in this method.
You can do that easily in a curses (full-screen) application (by reading the characters from the virtual screen using winch or win_wch), but would find it much harder in a termcap/terminfo low-level application because there is no portable method for reading directly from the terminal's screen.

connect four - comparison of evaluation - c

I try to implement the minimax algorithm into my connect four game.
I´m done with the evaluation-function and halfway done with the algorithm-function.
I just can`t find the solution for the "last" problem. Here are my functions:
void minimax(field f){
int i;
field c;
convert_1D_to_2D(f, c);
for(i=0;i<COLS;i++) {
if(can_throw(c, i) == 0) {
throw(f, i);
convert_1D_to_2D(f, c);
if((is_winner(c) == 0) && (is_board_full(f) == 0)) { //no winner, board not full
minimax(f);
}
else if(is_winner(c) == 1) { //there is a winner
evaluate_turn(f);
//compare evaluation
undo_turn(f);
}
else if(is_winner(c) == 0 && (is_board_full(f) == 1)) { //no winner, board full
evaluate_turn(f);
//compare evaluation
undo_turn(f);
}
}
}
The field is an array with f[COLS*ROWS+1], where f[0] is the depth and the other elements save in which columns were thrown. the "c"-board represents the "graphical" board with 0 for free, 1 for player 1 and 2 for player 2.
static int evaluate_turn(field f) {
field c;
convert_1D_to_2D(f, c);
if (((f[0] % 2) == 1) && (current_player == 1) && (is_winner(c) == 1) ) { //player 1 won, max for him || +1
return 1;
}
else if (((f[0] % 2) == 2) && (current_player == 2) && (is_winner(c) == 1) ) { //player 2 won, max for him || +1
return 1;
}
if (((f[0] % 2) == 1) && (current_player == 2) && (is_winner(c) == 1) ) { //player 2 won, counting for 1 || -1
return -1;
}
else if (((f[0] % 2) == 2) && (current_player == 1) && (is_winner(c) == 1) ) { //player 1 won, counting for 2 || -1
return -1;
}
else if ((is_board_full(f) == 1) && (is_winner(c) == 0)) { //draw || 0
return 0;
}
So my problem is, that i can't think of a clean solution to compare the evaluation bottom to top. I really think, that I don't need to introduce a new datastructure (which would get way too big). It's like the solution is right in front of me but i can't grab it.
Is it possible to just compare the evaluation on the "way back" of the recursion? If yes, how?
Or do I really need to introduce something new more complex? Or maybe I'm missing off something completely?
Thanks!
Or do I really need to introduce something new more complex? Or maybe
I'm missing off something completely?
Unfortunately the answer is the latter. Minimax is not a void function. It returns the value of the node that it represents. That is how evaluation is compared. You are also missing another fundamental concept. Your function only considers terminal nodes to be those where the game is won or the board is full. While this is technically true, no real minimax function works that way. The number of nodes would be around 7^48, so your function would literally take upwards of ten years to terminate on a modern pc. What real world minimax functions do is set a maximum depth for the search to reach (unless you add tree pruning expect this to be 5 or 6), and consider all nodes at that depth to be terminal and evaluate them using a heuristic (inexact guess) evalation function. In connect four this could be based on something like the number of three in a rows. Another mistake you made is calling your eval function if you know there is a winner. If you know which player won than return the proper value straight out, no need to call the expensive eval function. You also cannot stream line your function for both min and max as you did. You must either create a seperate function for min and max, or use the negamax variant.
My advise: It seems you don't really understand how the algorithm should be implemented. Read up on minimax and negamax psuedocode.

+= and incremental growth give two different values in C

I have a chunk of code that is measuring the length of a block of text. I need the length of a gap of an unknown number of N inserted within the text (which consists of G, A, C, and T only) as well as the total length of the text block containing the gap(s). I am working one character at a time via a fgetc() and I devised two different ways to calculate the values, but they are giving me vastly differing results.
Method A:
...
} else if (in != '\n') {
scafLength++;
if (in == 'N') {
//Read entire gap
while ((in != 'G') && (in != 'A') && (in != 'C') && (in != 'T') && (in != '>')) {
if (in != '\n'){
gapLength++;
scafLength++;
}
in = fgetc (inFile);
//If it's at the end of the file
if (feof (inFile)) {
break;
}
}
...
Do stuff
...
//Reset for next gap and allow normal processing of next character after the gap
gapLength = 0;
fseek (inFile, -1, SEEK_CUR);
}
}
Method B:
...
} else if (in != '\n') {
scafLength++;
if (in == 'N') {
//Read entire gap
while ((in != 'G') && (in != 'A') && (in != 'C') && (in != 'T') && (in != '>')) {
if (in != '\n'){
gapLength++;
}
in = fgetc (inFile);
//If it's at the end of the file
if (feof (inFile)) {
break;
}
}
scafLength += gapLength - 1;
...
Do stuff
...
//Reset for next gap and allow normal processing of next character after the gap
gapLength = 0;
fseek (inFile, -1, SEEK_CUR);
}
}
> is a character used to denote a new scaf. This is the only area where scafLength and gapLength are altered, except to set them back to 0 for a new gap/scaf. Now, I expected an off-by-one in method A, which is why I made method B, but the numbers I'm getting are way off. Method A is giving me 16,777,216 as the longest scaf while Method B gives me 23,080,784. The real longest scaf (verified by multiple other programs) is 23,428,386 and there are not 5 million gaps to account for a fencepost error (the most is 180).
I'm curious why would these two approaches give such drastic differences? Also, if anyone can see a mistake I'm making, I'd appreciate it being pointed out.
EDIT: From the first few comments I need to clarify, the gapLength is reset to 0 after it serves it's purpose in the same else if (). I've updated the code.
In the first version it looks like you only incrementing scafLength when (in != '\n') but in the second version you continually add the value of gapLength - 1 whenever you enter the outer if-block and not just when you enter the inner (in != '\n')
Presumably the value of gapLength isn't reset and therefore the second version grows faster.
As your code is incomplete it's really hard to say, so consider this a guess.
Turns out the issue was with my variable type caused by my compiler. gapLength and scafLength were originally declared as int. Having run out of options, I switch them to long and the code performs perfectly. Apparently my compiler has the short int limit of 32,768.

Equation returning 1.#QO

I've tried searching for anything similar about my issue on several websites, including this one, but none I've found so far are similar. After searching about the term 1.#QO, I found something about quiet NaN, but I'm new to C in general, so I don't really understand the issue .
I'm trying to take the x and y values of a joystick, and when then use a formula for distance to find the distance between the joystick's position, and the joystick's natural resting position (0,0).
If it matters, I'm trying to do this in RobotC.
#pragma config(Hubs, S1, HTMotor, none, none, none)
#pragma config(Sensor, S1, , sensorI2CMuxController)
#pragma config(Motor, mtr_S1_C1_1, DriveMotor, tmotorTetrix, openLoop)
//*!!Code automatically generated by 'ROBOTC' configuration wizard !!*//
#include "JoystickDriver.c"
int calculateDrivePower(int joyStickX, int joyStickY)
{
if (joyStickX != 0 & joyStickY != 0)
{
int joyDistance = (sqrt(pow((joyStickX - 0),2)+ pow((-joyStickY - 0),2)));
joyDistance = ((joyDistance/127)*100);
return (joyDistance);
}
else
{
return 0;
}
}
task main()
{
int previousJoySlope = 0;
int TurnSpeed = 70;
while (true)
{
getJoystickSettings(joystick);
if (abs(joystick.joy1_x1) > 10 || abs(joystick.joy1_y1) > 10)
{
writeDebugStreamLine("Test successful.");
motor[DriveMotor] = calculateDrivePower(joystick.joy1_x1,joystick.joy1_y1);
}
}
}
If anyone could provide any insight, that'd be fantastic, thanks.
if (joyStickX != 0 & joyStickY != 0)
{
int joyDistance = (sqrt(pow((joyStickX - 0),2)+ pow((-joyStickY - 0),2)));
joyDistance = ((joyDistance/127)*100);
return (joyDistance);
}
The first issues that appears is the conditional within the if statement. The you have a single & that most likely should be &&:
if (joyStickX != 0 && joyStickY != 0)
(note: likely should be is used above because you can provide a conditional using a logical & of the tests joystickx != 0, but in this case it provides the same result. In that case, I would suggest the more readable && be used)
The next part of the code is simply the vector distance between 0,0 and the present position of the joystick. Of the general form dist^2 = (x2-x1)^2 + (y2-y1)^2 in your case x1,y1 = 0,0. Taking the square root of both sides provides dist = sqrt((x2-x1)^2 + (y2-y1)^2), or in C notation:
dist = (sqrt(pow((joyStickX - 0),2)+ pow((-joyStickY - 0),2)));
Next you have a scaling applied of dist = dist * 100/127 which provides the final distance returned. Hopefully this will help you understand what the code is doing.

Graphical intersection of lines in C

I have a homework.
The homework is: There are 3 lines, theirs end with squares. Firstly The program has to view a circle is the lines are cut each other. (In other way: Take the intersection of the 3 lines). Secondly, the program has to change the background, along the lines. Each line's both side define the background with a colour. And how rotating the lines, together with them, the background colour changing.
There are 3 lines, and 6 background colour. The border of background color is along the lines.
The programming enviroment is the DevC++ (we must use the c++ console applicaton, but in the lesson we not coding in c++, just c...)
Youtube video about the exercise/homework
I've tried implement of the lines' intersection, but It doesn't work very well.
And I don't have any idea, how can I implement of the colourful background change.
What kind of knowledge is needed for it?
I would like to if somebody can suggest to me some: algorithm, webpage, tutorial, sourecode, anything what can help me. Or what is the name of my homework in english ( to google search)
Cause I don't think, my solution is the best way to prepare my homework (maybe it won't succes)
Here the code, that I have did up to now (but it not perfect. The intersection of lines is not perfectly. It's not a beautiful solution, sorry I am not an expert C programmer):
sourcode in english
PONT = point, dot
PONTH = aggregation of points
atir = rewrite
metszilleszt = fitting of intersection
szakasz = section, phase... (there is too many in english-hungarian) or platoon :-D
eger = mouse
egérkezelés = mouse control
balgomb = left button of mouse
# include "graphics.h"
# include <conio.h>
#include <stdio.h>
typedef struct {
float x1,x2,x3;
} PONTH;
typedef struct {
double x,y;
}PONT;
PONTH atir(PONT A){
PONTH C;
C.x1=A.x;
C.x2=A.y;
C.x3=1;
return C;
}
PONTH metszilleszt(PONTH A,PONTH B){
PONTH C;
C.x1=(A.x2*B.x3)-(A.x3*B.x2);
C.x2=-(A.x1*B.x3)+(A.x3*B.x1);
C.x3=(A.x1*B.x2)-(A.x2*B.x1);
return C;
}
int main()
{
//PONT szakasz[4]={100,50,300,200,30,130,140,170};
PONT szakasz[6]={100,50,300,200,30,130,140,170,30,70,210,40};
int ap;
int gd,gm;
int page =0;
gd=VGA;gm=VGAMED;
initgraph(&gd,&gm,"");
PONTH A,B,C,D,E,F;
PONTH tmp1,tmp2,tmp3,tmp4,tmp5,tmp6;
PONT pont;
for(;;){
setactivepage(page);
cleardevice();
A=atir(szakasz[0]);
B=atir(szakasz[1]);
C=atir(szakasz[2]);
D=atir(szakasz[3]);
E=atir(szakasz[4]);
F=atir(szakasz[5]);
tmp1=metszilleszt(A,B);
tmp2=metszilleszt(C,D);
tmp3=metszilleszt(E,F);
tmp4=metszilleszt(tmp2,tmp1);
tmp5=metszilleszt(tmp3,tmp1);
tmp6=metszilleszt(tmp3,tmp2);
pont.x=int (tmp3.x1/tmp3.x3);
pont.y=int (tmp3.x2/tmp3.x3);
//printf("%f %f\n",pont.x,pont.y);
// good
if((((tmp4.x2/tmp4.x3)>=szakasz[0].y) && ((tmp4.x2/tmp4.x3)<=szakasz[1].y)) &&
(((tmp4.x1/tmp4.x3)>=szakasz[0].x) && ((tmp4.x1/tmp4.x3)<=szakasz[1].x)) ||
(((tmp4.x2/tmp4.x3)>=szakasz[0].y) && ((tmp4.x2/tmp4.x3)<=szakasz[1].y)) &&
(((tmp4.x1/tmp4.x3)<=szakasz[0].x) && ((tmp4.x1/tmp4.x3)>=szakasz[1].x)))
{
setcolor(RED);
fillellipse(int (tmp4.x1/tmp4.x3),int (tmp4.x2/tmp4.x3),5,5);
}
if((((tmp5.x2/tmp5.x3)>=szakasz[0].y) && ((tmp5.x2/tmp5.x3)<=szakasz[1].y)) &&
(((tmp5.x1/tmp5.x3)>=szakasz[0].x) && ((tmp5.x1/tmp5.x3)<=szakasz[1].x)) ||
(((tmp5.x2/tmp5.x3)>=szakasz[0].y) && ((tmp5.x2/tmp5.x3)<=szakasz[1].y)) &&
(((tmp5.x1/tmp5.x3)<=szakasz[0].x) && ((tmp5.x1/tmp5.x3)>=szakasz[1].x)))
{
setcolor(RED);
//fillellipse(int (tmp5.x1/tmp5.x3),int (tmp5.x2/tmp5.x3),5,5);
fillellipse(int (tmp5.x1/tmp5.x3),int (tmp5.x2/tmp5.x3),5,5);
}
if((((tmp6.x2/tmp6.x3)>=szakasz[0].y) && ((tmp6.x2/tmp6.x3)<=szakasz[1].y)) &&
(((tmp6.x1/tmp6.x3)>=szakasz[0].x) && ((tmp6.x1/tmp6.x3)<=szakasz[1].x)) ||
(((tmp6.x2/tmp6.x3)>=szakasz[0].y) && ((tmp6.x2/tmp6.x3)<=szakasz[1].y)) &&
(((tmp6.x1/tmp6.x3)<=szakasz[0].x) && ((tmp6.x1/tmp6.x3)>=szakasz[1].x)))
{
setcolor(RED);
fillellipse(int (tmp6.x1/tmp6.x3),int (tmp6.x2/tmp6.x3),5,5);
}
//else{ setcolor(RED);
// fillellipse(int (tmp3.x1/tmp3.x3),int (tmp3.x2/tmp3.x3),5,5); }
/* Egerkezeles */
if (!balgomb) ap = getactivepoint((pont2d*)szakasz,6,6);
if (ap >= 0 && balgomb)
{
szakasz[ap].x = egerx;
szakasz[ap].y = egery;
}
/* Egerkezeles vege */
setcolor(WHITE);
line((int)szakasz[0].x,(int)szakasz[0].y,(int)szakasz[1].x,(int)szakasz[1].y);
rectangle((int)szakasz[0].x,(int)szakasz[0].y, (int)szakasz[0].x+4, (int)szakasz[0].y+4);
rectangle((int)szakasz[1].x,(int)szakasz[1].y, (int)szakasz[1].x+4, (int)szakasz[1].y+4);
line((int)szakasz[2].x,(int)szakasz[2].y,(int)szakasz[3].x,(int)szakasz[3].y);
rectangle((int)szakasz[2].x,(int)szakasz[2].y, (int)szakasz[2].x+4, (int)szakasz[2].y+4);
rectangle((int)szakasz[3].x,(int)szakasz[3].y, (int)szakasz[3].x+4, (int)szakasz[3].y+4);
line((int)szakasz[4].x,(int)szakasz[4].y,(int)szakasz[5].x,(int)szakasz[5].y);
rectangle((int)szakasz[4].x,(int)szakasz[4].y, (int)szakasz[4].x+4, (int)szakasz[4].y+4);
rectangle((int)szakasz[5].x,(int)szakasz[5].y, (int)szakasz[5].x+4, (int)szakasz[5].y+4);
setvisualpage(page);
page = 1-page;
if (kbhit()) break;
}
getch();
closegraph();
return(0);
}
Regarding the intersections of lines, you should read the article of Loren Shure and Lucio Cetto from Matworks on Loren's blog:
Part 1
Part 2
It's in Matlab but the principles are the same.

Resources