gpt4 book ai didi

c - 添加程序在我给它输入时崩溃

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

我是 C 初学者,这是迄今为止我最大的程序。它包含 do while 循环以重新启动程序,允许用户添加任意​​数量的数字并确保提交正确的字母以表示是或否。很简单。问题是,我键入的每个数字加起来都是 0.00,无论我选择重新启动,程序都会给我一个段错误(核心转储)错误。

错误:

Program Errors

我很清楚这可能是我忽略的一些愚蠢的细节,但请耐心等待!非常感谢您的帮助。

代码:

/*Basic addition program*/
/*May 31 2018*/
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
int main()
{
char restart;

//Loop for restart
do{
/*
Starts Variables for Current number, sum,
number place count, and restart choice
*/
float currnum, sum;
int count = 1;
char restart = 'N';

//Loop for user input amount until 0 is submitted
do{

//Initiates number place ending array
char end[3];

printf("Basic Addition Program\nType 0 To Terminate\n\n");

//Chooses which ending to add to array
if(count == 1){
strcpy(end, "st");
}else if(count == 2){
strcpy(end, "nd");
}else if(count == 3){
strcpy(end, "rd");
}else if(count > 3){
strcpy(end, "th");
}

//Requests user input and adds to current number float
printf("Enter %d%s number: ", count, end);
scanf(" %d", &currnum);

//Clears Screen (Unix)
system("clear");

//Adds current number to overall sum
sum += currnum;

//Increases number count so that places shift by 1 (e.g 1st to 2nd)
count++;


}while(currnum != 0);

//States numbers inputted and sum
printf("You added %d numbers and got a sum of %.2f\n", count, sum);

//Do while loop for user error
do{
printf("Restart?(Y/N): ");
scanf(" %c", restart);

//Tests if numbers have ben inputted in lowercase and corrects accordingly
if(restart == 'y'){
restart = 'Y';
}else if(restart == 'n'){
restart = 'N';
}
}while(restart != 'Y' || restart != 'N' );

}while(restart == 'Y');

return 0;
}

最佳答案

有问题的陈述之一是

scanf(" %c", restart); /* you need to provide the &(address) to store */

应该是

scanf(" %c", &restart);

您应该阅读编译器警告并自行解决并使用 -Wall 标志进行编译。

还有下面的声明

scanf("%d", &currnum); /* currnum is declared as float variable, use %f */

在下面的代码块中

char restart;
do {

/* some code */
}while(restart == 'Y');

restart 未初始化,您的编译器可能会警告您

error: ‘restart’ is used uninitialized in this function [-Werror=uninitialized]

所以在最开始的时候像restart一样初始化

char restart = 'Y';

最后,如果您想正确学习 C,请将所有警告视为错误,然后开始解决问题。例如像下面这样编译

gcc -Wall -pedantic -Wstrict-prototypes -Werror test.c

关于c - 添加程序在我给它输入时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50627717/

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