gpt4 book ai didi

C程序函数错误

转载 作者:行者123 更新时间:2023-11-30 20:20:51 25 4
gpt4 key购买 nike

此代码必须获取坐标并将其写入 coords 数组,并返回已输入的坐标数。

一旦用户输入 0 0,代码就必须停止,但代码不应保存它。

例如,如果我输入 1 2 3 4 0 0,代码会将数组设置为 (1,2) (3,4)

但是在这段代码中,当我输入 0 0 时,它会显示错误,一旦我首先输入数字,打印结果只会显示零。

int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
++row;
}

printf("%.3lf %.3lf", coords[row][0], coords[row][1]); /* TEST */

}
return row+1;
}

最佳答案

问题是,当您打印 coords[row][0] 和 coords[row][1] 时,您实际上是将用户尚未输入的下一个坐标发送到 stdout。您正在向标准输出发送未定义的值,而不是您输入的值。 printf("%.3lf %.3lf", coords[row][0], coords[row][1]); 行应为 printf("%.3lf %. 3lf\n", coords[row-1][0], coords[row-1][1]); 并添加下一行 \n 否则打印的信息为难以辨认。

试试这个代码

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

#define DIM 2

int coordinatesread(double coords[][DIM], int n)
{
double columnin, rowin;
int row=0;
while(row!=n-1)
{
scanf ("%lf",&columnin);
scanf ("%lf",&rowin);
if (columnin==0 && rowin==0)
{
return row+1;
}
else
{
coords[row][0]=columnin;
coords[row][1]=rowin;
row++;
}
printf("%.3lf %.3lf\n", coords[row-1][0], coords[row-1][1]); /* TEST */
}
return row+1;
}

int main(void)
{
double cords[5][2];
int n = 5;

coordinatesread(cords, n);

return 0;
}

关于C程序函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44595666/

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