I am creating digital clock with an output using ascii and I made a large number consisting of five lines. I want to move the number using gotoxy but only the first line moves and the rest line is ignoring the y coordinates.
How can I move my entire number using gotoxy while my printf has newlines?
#include <stdio.h>
#include <time.h>
#include <windows.h>
#include<conio.h>
void gotoxy(int col, int row);
void disp0();
int count=219;
int main()
{
gotoxy(10,10);disp0();
}
void gotoxy(int col, int row)
{
COORD coord;
coord.X = col; coord.Y = row;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}
void disp0(){
printf("%c%c%c\n%c %c\n%c %c\n%c %c\n%c%c%c",count,count,count,count,count,count,count,count,count,count,count,count);//0
}
This is the output I get:
You need to do a gotoxy and a printf for every individual digit. No \n should be used. If you want to be fancy you can use trigonometry, like in this very sloppy example:
#include <stdio.h>
#include <windows.h>
#include <math.h>
void gotoxy(int x, int y)
{
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),
(COORD){ .X=x, .Y=y });
}
int main()
{
const int center_x = 12;
const int center_y = 12;
const int radius = 6;
double angle = 0;
int clock [12] = {3, 2, 1, 12, 11, 10, 9, 8, 7, 6, 5, 4};
for(int i=0; i<12; i++)
{
int x = round(radius * cos(angle));
int y = round(radius * -sin(angle)); // - to shift y axis on console coord system
angle += (2.0 * 3.1415) / 12.0;
// 2*x rough estimate to compensate for font height vs width:
gotoxy(center_x + 2*x, center_y + y);
printf("%d", clock[i]);
}
gotoxy(1,center_y*2);
}
Ugly output:
12
11 1
10 2
9 3
8 4
7 5
6
Related
The input to my program is a (x, y) integer coordinate inside the blue region of this circle of radius 100. I want to scale the input coordinate from the blue area to the red area, maintaining the the x and y ratios.
(link to the Desmos plot: https://www.desmos.com/calculator/61f4y2r7r4)
I know how to do this with one dimension - this answer gives a good overview on performing linear scaling. I attempted to apply this approach to the x and y axes separately. Here is some example code that I wrote to model the image.
#include <math.h>
#include <stdio.h>
#define RADIUS 100
static int find_point_on_circumference(int val) {
return sqrt(RADIUS * RADIUS - val * val);
}
static int scale(int val, int min_old, int max_old, int min_new, int max_new) {
return (max_old == min_old)
? val
: (((val - min_old) * (max_new - min_new)) / (max_old - min_old) + min_new);
}
int main() {
int x = 15;
int y = 96;
int boundary_old_x = 10;
int boundary_old_y = 10;
int boundary_new_x = 30;
int boundary_new_y = 20;
int new_x = scale(
x,
boundary_old_x,
find_point_on_circumference(y),
boundary_new_x,
find_point_on_circumference(y));
int new_y = scale(
y,
boundary_old_y,
find_point_on_circumference(x),
boundary_new_y,
find_point_on_circumference(x));
if (sqrt(new_x * new_x + new_y * new_y) <= RADIUS) {
printf("SUCCESS\n");
} else {
printf("FAIL\n");
}
return 0;
}
For this particular input, (15, 96), the result is outside of the circle. I can see that the reason for that is that my max-x bound is less than my min-x bound. I'm just not sure how I should be applying this scaling correctly in the first place.
I am working on C graphics program, where I will ask for Projection Angle from end user and then will use that angle to launch the rocket from earth (circle) surface.
But I am not able to do so.
Here what I found on google:
x1 = x + cos(angle) * distance;
y1 = y + sin(angle) * distance;
where x1 y1 are the new pixel position for object.
I tried this but it doesn't seem like working. Also I want rocket to move constantly till the end of screen, but the above code will directly print the object from position A to position B.
Complete Program Code
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <dos.h>
#include <math.h>
#include <stdlib.h>
#include <iostream.h>
#define cld cleardevice()
int _moonRadius = 20, _earthRadius = 40, _marsRadius = 25;
void mars () {
setfillstyle(9, BROWN);
setcolor(BROWN);
circle(getmaxx() - 25, 50, _marsRadius);
floodfill(getmaxx() - 27, 52, BROWN);
}
void moon () {
setfillstyle(9, WHITE);
setcolor(WHITE);
circle(getmaxx()/2, getmaxy()/2, _moonRadius);
floodfill(getmaxx()/2, getmaxy()/2, WHITE);
// Moon's gravitational area
setfillstyle(SOLID_FILL, DARKGRAY);
setcolor(DARKGRAY);
circle(getmaxx()/2, getmaxy()/2, _moonRadius * 5);
}
void earth () {
setfillstyle(9, GREEN);
setcolor(GREEN);
circle(40, getmaxy() - 100, _earthRadius);
floodfill(42, getmaxy() - 102, GREEN);
}
void rocket (int x, int y) {
setcolor(WHITE);
rectangle(x, y - 105, x + 70, y - 95);
}
void rocket_clear (int x, int y) {
setcolor(BLACK);
rectangle(x, y - 105, x + 70, y - 95);
}
void main () {
clrscr();
int angle, speed;
printf("Please provide input parameters.");
printf("Enter projection angle (range from 5 to 90)\n");
scanf("%d", &angle);
printf("Enter projection speed (range from 10 to 100)\n");
scanf("%d", &speed);
int gd=DETECT, gm, i, j, k;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
// Planets and rocket
mars();
moon();
earth();
rocket(80, 550); // let say initial pixel position x = 80, y = 550
// Moving the rocket
// Right now its only moving towards horizontal line, with speed implementation
// Now here I want to implement the angle of projection
for (i = 81; i < getmaxx() + 100; i++) {
// Also I am not sure about this loop's final range, should it go to getmaxx() or some other range
rocket(i, 550);
rocket_clear(i - 1, 550); // 550 is hard coded right now, so rocket will move only horizontally
delay(500 / speed);
}
getch();
}
Need your help guys, please.
(For reference: you can also think of a moving bullet from killer position to the position of person with some angle)
Thanks :)
Please read the comments starting with //=====
#include <stdio.h>
#include <conio.h>
#include <graphics.h>
#include <dos.h>
#include <math.h>
#include <stdlib.h>
#include <iostream.h>
#define cld cleardevice()
//===== making these values as constants
static const int _moonRadius = 20, _earthRadius = 40, _marsRadius = 25;
static double projection_angle = 0.0;
void mars () {
setfillstyle(9, BROWN);
setcolor(BROWN);
circle(getmaxx() - _marsRadius, 50, _marsRadius);
floodfill(getmaxx() - 27, 52, BROWN);
}
void moon () {
setfillstyle(9, WHITE);
setcolor(WHITE);
circle(getmaxx()/2, getmaxy()/2, _moonRadius);
floodfill(getmaxx()/2, getmaxy()/2, WHITE);
// Moon's gravitational area
setfillstyle(SOLID_FILL, DARKGRAY);
setcolor(DARKGRAY);
circle(getmaxx()/2, getmaxy()/2, _moonRadius * 5);
}
void earth () {
setfillstyle(9, GREEN);
setcolor(GREEN);
circle(40, getmaxy() - 100, _earthRadius);
floodfill(42, getmaxy() - 102, GREEN);
}
void rocket (int x, int y) {
setcolor(WHITE);
//===== a box of size 10x10
rectangle(x, y, x + 10, y - 10);
}
void rocket_clear (int x, int y) {
setcolor(BLACK);
//===== a box of size 10x10
rectangle(x, y, x + 10, y - 10);
}
void main () {
clrscr();
int angle, speed;
printf("Please provide input parameters.");
printf("Enter projection angle (range from 5 to 90)\n");
scanf("%d", &angle);
//===== angle validation
if (angle < 5 || angle > 90)
{
printf("Please provide angle in range [5, 90]\n");
getch();
return;
}
//===== calculate angle in radians
projection_angle = (angle * 3.14) / 180.0;
printf("projection_angle = %d\n", projection_angle);
printf("Enter projection speed (range from 10 to 100)\n");
scanf("%d", &speed);
//===== speed validation
if (speed < 10 || speed > 100)
{
printf("Please provide speed in range [10, 100]\n");
getch();
return;
}
int gd=DETECT, gm, i, j, k;
initgraph(&gd, &gm, "C:\\TURBOC3\\BGI");
// Planets and rocket
mars();
moon();
earth();
rocket(80, 550); // let say initial pixel position x = 80, y = 550
// Moving the rocket
// Right now its only moving towards horizontal line, with speed implementation
// Now here I want to implement the angle of projection
//===== to store prev position
int prev_i = 0, prev_j = 0;
//===== increments will be constant for a given angle and speed
const int x_inc = cos(projection_angle) * speed;
const int y_inc = sin(projection_angle) * speed;
//===== i and j will be updated with their respective increments
for (i = 90, j = getmaxy() - 100; i < getmaxx() + 100 && j >= -10; i += x_inc, j -= y_inc) {
// Also I am not sure about this loop's final range, should it go to getmaxx() or some other range
//===== clear the previous position
rocket_clear(prev_i, prev_j); // 550 is hard coded right now, so rocket will move only horizontally
//===== draw rocket at current position
rocket(i, j);
//===== make current position as previous position
prev_i = i;
prev_j = j;
//printf("x_inc = %lf, y_inc = %lf\n", cos(projection_angle) * speed, sin(projection_angle) * speed);
delay(500 / speed);
}
getch();
}
Note: You can replace 3.14 with actual Pi. Refer this.
Be sure that you are passing the angle in radians. To convert from degrees: radians=degrees*PI/180 (PI is defined in math.h which should be included by graphics.h) Make sure your variables are doubles.
Next you will probably want to bundle your X/Y coordinates in a struct so you can return the new position from a function:
typedef struct {
double x;
double y
} coord_t;
coord_t new_pos(double x, double y, double distance, double angle_deg) {
coord_t result;
double angle_rad = angle_deg * PI / 180;
result.x = x + cos(angle_rad) * distance;
result.y = y + sin(angle_rad) * distance;
return result;
}
Or you could handle all the angles in radians so the function doesn't have to do the extra calculation.
As I see it the numerical sequence consists of 2 separate sequences. This is the code that I have so far. I am not sure if you must use a while or a for loop. I am fairly new at coding so if someone please could help me.
if the entered value is 10 it must give the first 10 terms of the sequence, and if I enter 5 it must give me the first 5 terms of the sequence.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main() {
int a, n = 1, t, y = 1; // First Numerical Sequence
int b, m = 2, s, x = 2; // Second Numerical Sequence
int d, r, z; // Extra
printf("Enter A Tn : ");
scanf(" %d", &z);
printf("\n");
while (n <= z) {
a = 15;
r = pow(2, n - y);
d = (9 * (r - 1)) / (2 - 1);
t = a + d;
printf("%d\n", t);
n += 2;
y++;
}
while (m <= z) {
b = 12;
r = pow(2, m - x);
d = (9 * (r - 1)) / (2 - 1);
s = b + d;
printf("%d\n", s);
m += 2;
x++;
}
printf("\n");
return 0;
}
This will get the job done.
#include <stdio.h>
int main(){
int val,ic; //iteration count, will print ic*2 number
scanf("%d %d",&val,&ic);
for(int i = 0;i<ic;i++){
printf("%d ",val);
val-=3;
printf("%d ",val);
val*=2;
}
printf("\n");
}
How to compile & run:
C:\Users\stike\Desktop>rem assume you saved it in a.c
C:\Users\stike\Desktop>gcc -o a a.c
C:\Users\stike\Desktop>a
15
5
15 12 24 21 42 39 78 75 150 147
If you want to print the same sequence starting from 15 and o till a certain number which the user inputs, you can follow the following code.
Hope you understood the sequence pattern when a number is given it is printed and reduce the number by 3, then it is printed and then twice the number and printed, and again reduce by 3, likewise, it flows on.
#include <stdio.h>
int main() {
int endNum;
int beginNum = 15;
printf("Enter the end: ");//(lineA) here we initialize the variables with beginNum as 15
scanf("%d", &endNum); //(Line B) let the user to input endNum of the sequence,in the example it is 147
while ((beginNum-3) <= endNum) { // checks the condition
printf("%d ", beginNum);
if(beginNum==endNum) return 0; //check whether you print the end number.
beginNum -= 3; // reduce by 3
printf("%d ", beginNum);
beginNum *= 2; // multiply by 2
}
return 0;
}
if you don't need to user input a endNum just initialize the value 147 to variable endNum.
And delete the lines A and B.
Here's another approach using static variables
#include <stdio.h>
int next(void) {
static int last, n = 0;
if (n++ == 0) return last = 15; // 1st element of sequence
if (n % 2) return last = last * 2; // odd elements
return last = last - 3; // even elements
}
int main(void) {
for (int k = 0; k < 10; k++) {
printf("%d ", next());
}
puts("");
return 0;
}
I am not a specialist in C programming and Linux OS development, but I have a task about making screenshots on Ubuntu and Fedora OS. After searching on the internet I found a lot of topics and questions about how to do it using C language and libX11. Finally, I combined all I could find in one method which captures the screenshot and saves to .png file.
I have two virtual machines installed - one is Ubuntu 18.04, the second is Fedora 30. When I run my code on Ubuntu - it works perfectly, when I run it on Fedora - I have a screenshot file with black content.
My code is:
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/extensions/XShm.h>
#include <stdio.h>
#include <inttypes.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cairo.h>
#include <cairo-xlib.h>
#include <stdlib.h>
int get_shift (int mask) {
int shift = 0;
while (mask) {
if (mask & 1) break;
shift++;
mask >>=1;
}
return shift;
}
void takeScreenshot() {
Display *d;
int s;
XImage *image;
XShmSegmentInfo shminfo;
d = XOpenDisplay(NULL);
s = DefaultScreen(d);
unsigned int width = DisplayWidth(d,s);
unsigned int height = DisplayHeight(d,s);
image = XShmCreateImage(d,
DefaultVisual(d,s), // Use a correct visual. Omitted for brevity
24, // Determine correct depth from the visual. Omitted for brevity
ZPixmap, NULL, &shminfo, width, height);
shminfo.shmid = shmget(IPC_PRIVATE,
image->bytes_per_line * image->height,
IPC_CREAT|0777);
shminfo.shmaddr = image->data = shmat(shminfo.shmid, 0, 0);
shminfo.readOnly = False;
XShmAttach(d, &shminfo);
XShmGetImage(d,
RootWindow(d,s),
image,
0,
0,
AllPlanes);
cairo_surface_t *surface;
int stride;
stride = cairo_format_stride_for_width(CAIRO_FORMAT_RGB24, width);
unsigned char *data = malloc(stride * height);
int redShift = get_shift(image->red_mask);
int greenShift = get_shift(image->green_mask);
int blueShift = get_shift(image->blue_mask);
printf("r_shift: %d; g_shift: %d; b_shift: %d\n",redShift, greenShift, blueShift);
printf("byte order: %d\n", image->byte_order);
printf("bytes per line: %d\n", image->bytes_per_line);
printf("bites per pixel: %d\n", image->bits_per_pixel);
printf("r_mask: %lu; g_mask: %lu; b_mask: %lu\n", image->red_mask, image->green_mask, image->blue_mask);
printf("bitmap_bit_order: %d bitmap_pad: %d format: %d xoffset: %d\n", image->bitmap_bit_order, image->bitmap_pad, image->format, image->xoffset);
int x, y;
for (y = 0; y < height; ++y){
for (x = 0; x < width; ++x) {
unsigned long pixel = XGetPixel(image, x, y);
unsigned char red = (image->red_mask & pixel)>>redShift;
unsigned char green = (image->green_mask & pixel)>>greenShift;
unsigned char blue = (image->blue_mask & pixel)>>blueShift;
data[y * stride + x * 4 + 0] = blue;
data[y * stride + x * 4 + 1] = green;
data[y * stride + x * 4 + 2] = red;
}
}
surface = cairo_image_surface_create_for_data(
data,
CAIRO_FORMAT_RGB24,
width, height,
stride);
cairo_status_t surfaceStatus = cairo_surface_status(surface);
const char *r = cairo_status_to_string (surfaceStatus);
printf("%s\n", &r[0]);
int writepngRes = cairo_surface_write_to_png(
surface,
"test.png");
printf("surf status: %d; write result: %d\n", surfaceStatus, writepngRes);
cairo_surface_destroy(surface);
}
int main(int argc, char* argv[]) {
takeScreenshot();
return 0;
}
And I build this code using following command:gcc code.c -o code.so -lXss -lX11 -lXext -fPIC -I/usr/include/cairo -lcairo
The setup is exactly the same on both machines, what I have checked is that bit mask, byte order and bytes per pixel are equal for both systems. I am asking for suggestions about how to find a bug reason, maybe advice which thing to debug. Thank you!
UPDATE:
When I run this code on both platforms I see exactly the same output:
r_shift: 16; g_shift: 8; b_shift: 0
byte order: 0
bytes per line: 5464
bites per pixel: 32
r_mask: 16711680; g_mask: 65280; b_mask: 255
bitmap_bit_order: 0 bitmap_pad: 32 format: 2 xoffset: 0
no error has occurred
surf status: 0; write result: 0
I have an equation for finding the mid point value for the Riemann sum, but it is not providing the correct value for the midpoint when entering coefficients 3, 4, 0 and upper and lower limits of -1 and 1 with 10 rectangles.
float getMidPoint(int final, int initial, int rectangle, int coefficient1, int coefficient2, int coefficient3)
{
float deltaX;
float sumMidPoint;
float f_X;
float x;
x = initial;
deltaX = (final - initial) / rectangle;
while(x < final)
{
f_X = pow((coefficient1 * x), 2) + (coefficient2 * x) + coefficient3;
sumMidPoint += f_X * deltaX;
x = x + deltaX;
}
return (sumMidPoint);
}
I am not sure why I am not getting the correct value for sumMidPoint. The test case has the sumMidPoint = 1.980000 sq. units
Two issues:
final, initial and rectangle are all integers, therefore you're making an integer division:
(final - initial) / rectangle = 2/20 = 0.1 in float but 0 in int
to correct, set at least one of them as float, but better both:
float final, float initial
Your second error is in the formula: 3x^2 is 3 * pow(x, 2). You wrote (3x)^2.
Also, to be safe, don't forget to initialize your sumMidPoint variable before using it:
float sumMidPoint = 0;
Here is my final version of the code:
#include <stdio.h>
#include <math.h>
float getMidPoint(float final, int initial, int rectangle, int coefficient1, int coefficient2, int coefficient3) {
float deltaX = (final - initial) / rectangle;
float sumMidPoint = 0;
float f_X;
float x = initial + deltaX / 2;
for(int i=0; i< rectangle; i++)
{
f_X = (coefficient1 * pow( x, 2)) + (coefficient2 * x) + coefficient3;
sumMidPoint += f_X * deltaX;
x = x + deltaX;
}
return(sumMidPoint);
}
int main() {
printf("Result: %f\n", getMidPoint(1, -1, 10, 3, 4, 0));
return(0);
}
Output:
Result: 1.980000