gpt4 book ai didi

c - 导致段错误的公式 11

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

我不明白为什么当我输入数字 1 到 4 时,我在控制台中收到段错误 11。当我绕过速度公式时,它可以工作,但我不知道如何修复该公式。我为一项学校作业创建了这段代码,要求我打印 4 个结构数组并提示用户选择一个,然后使用用户选择的数组来计算该 channel 的速度并将其输出。

/*----------------------------------------
file: A4Q2.c
author: Wahhaaj Salam
description: Program presents the characteristics of four rectangular channels and prompts the user to select one of the channels and after calculate the chnnels velocity and displays results
-----------------------------------------------*/
#include <stdio.h>
#include <math.h>
// function prototypes

typedef struct
{
// variable declarations
char name[100]; // Channel name
float n; // roughness
float slope; // slope
float width; // width
float depth; // depth
} CHANNEL;

void printchannels(CHANNEL channels[4]);
float velocity(CHANNEL channels[4], int x);

void main (){
CHANNEL channels[4] =
{
{"Channel 1", 0.035, 0.0001, 10.0, 2,0},
{"Channel 2", 0.020, 0.0002, 8.0, 1.0},
{"Channel 3", 0.015, 0.0010, 20.0, 1.5},
{"Channel 4", 0.030, 0.007, 24.0, 3.0},

};
printchannels(channels);
int x;
float v;
printf("Make a selection(1 to 4):");
scanf("%f", &x);
v = velocity(channels,x);
printf("the velocity is: %f", v);
}

void printchannels(CHANNEL channels[4])
{
int i;
for ( i = 0; i <4; i++){
printf("%s ", channels[i].name);
printf("%.3f ", channels[i].n);
printf("%.4f ", channels[i].slope);
printf("%.1f ", channels[i].width);
printf("%.1f \n", channels[i].depth);

}

}

float velocity(CHANNEL channels[4], int x)
{
float v;
v=(channels[x-1].width/channels[x-1].depth);
v=v/(channels[x-1].width + (2*channels[x-1].depth));
v=pow(v,0.6666666666667);
v=v*(sqrt(channels[x-1].slope)/channels[x-1].n);
return v;
}

最佳答案

你声明

int x;

然后你错误地将x扫描为 float :值不可能在1和4之间

scanf("%f", &x);

然后将值传递给例程:数组越界!

正确的代码(可以保护您免受用户错误输入的影响)是:

while(1)
{
printf("Make a selection(1 to 4):");
scanf("%d", &x);
if ((x>0) && (x<5)) break; // boundary checking
}

关于c - 导致段错误的公式 11,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40075554/

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