gpt4 book ai didi

C:制作矩形错误

转载 作者:太空宇宙 更新时间:2023-11-04 03:38:02 25 4
gpt4 key购买 nike

我想制作一个带有“-”、“|”和大量空格的简单矩形。这是代码:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

#define MAX_NUMBER 25

void draw_height(int height, int width)
{
int i = 0;
for(i = 0; i <= (height-1); i++) {
printf("|");
for(i = 0; i <= (width-1); i++) {
printf(" ");
}
printf("|");
}
}

void draw_width(int width)
{
int i = 0;
printf(" ");
for(i = 0; i <= width; i++) {
printf("_");
}
}

void draw_height_final(int width)
{
printf("|");
int i = 0;
for(i = 0; i <= (width); i++) {
printf("_");
}
printf("|");

}
//make the rectangle
void make_rec(int w, int h)
{
draw_width(w);
draw_height(h, w);
draw_height_final(w);
}

//initiate the program
int main(int argc, char *argv[])
{
int rec_width;
int rec_height;
if(isdigit(argv[1]) && isdigit(argv[2])) {
rec_width = (int)argv[1];
rec_height = (int)argv[2];
if(rec_width < MAX_NUMBER && rec_height < MAX_NUMBER) {
make_rec(rec_width, rec_height);
} else {
printf("The max value is 25 for both\n");
}
} else {
printf("Inputs must be numbers\n");
}
return 0;
}

但是,当我在 Ubuntu 终端中使用 ./运行它时,它会打印出“Segmentation fault (core dumped)”。

我还注意到终端告诉我第 52 和 53 行存在转换问题。

求助!

最佳答案

   rec_width = (int)argv[1];
rec_height = (int)argv[2];

转换不会将 char* 转换为 int。您需要使用 strtol家庭功能可以做到这一点。

此外,isdigit 采用 int 参数,而您传递的是 char*。检查是否传递了参数的条件可以写成:

if (argc == 3) {
rec_width = ... /*conversion using strtol here with error checking*/
rec_height = ... /*conversion using strtol here with error checking*/
if(rec_width < MAX_NUMBER && rec_height < MAX_NUMBER) {
make_rec(rec_width, rec_height);
} else {
printf("The max value is 25 for both\n");
}
}
else {
printf("Inputs must be numbers\n");
}

关于C:制作矩形错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30679197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com