我在 NetBeans 上有一个脚本要求用户输入。因为“控制台类型”内部终端给我一个错误,所以我将控制台更改为标准输出。
它使用一个普通的简单代码,但是当我尝试在我的实际代码上运行它时,它在出现消息之前返回错误“运行失败(退出值 -1.073.741.819,总时间:79 毫秒)”输入。
代码如下:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int product, price, n_product, sum, num, canti, total;
printf("What's the number of products? ");
scanf( "%d", &n_product );
num=1;
sum=0;
while(num<=n_product) {
printf("What was the product? ");
scanf( "%s", product );
printf("What was the unit price? ");
scanf( "%d", &price );
printf("How much did you buy? ");
scanf( "%d", &canti );
total=price*canti;
sum=sum+total;
num++;
}
printf("Total is %n", sum);
return (EXIT_SUCCESS);
}
我已经搜索了错误,但没有出现任何结果,所以我真的不知道它有什么问题。
代码中没有一个未声明的变量。由于它在第一个 printf
后立即停止,我认为错误可能出在 scanf
上,但我不知道。
编辑:
我修改了如下代码:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
int price, n_product, sum, num, canti, total;
char product[20];
printf("What's the number of products? ");
scanf( "%d", &n_product );
num=1;
sum=0;
while(num<=n_product) {
printf("What was the product? ");
scanf( "%19s", product );
printf("What was the unit price? ");
scanf( "%d", &price );
printf("How much did you buy? ");
scanf( "%d", &canti );
total=price*canti;
sum=sum+total;
num++;
}
printf("Total is %d", sum);
return (EXIT_SUCCESS);
}
现在外部终端没有给我任何错误,但我根本无法输入,只是让我关闭它
最佳答案
product
变量声明为 int
,但是当您尝试为其输入一个值时,您可以这样做:
scanf( "%s", product );
如果 product
被定义为字符数组,这将是正确的,但事实并非如此。这取而代之的是获取 product
的当前值(未知,因为它未初始化)并将其传递给 scanf
,后者将其解释为指向字符数组的指针。这会调用 undefined behavior ,在本例中表现为崩溃。
将 product
的类型更改为字符数组,并修改对 scanf
的调用以告诉它该数组的大小:
char product[20];
...
scanf("%19s", product);
这是第一个问题。第二个在这里:
printf("Total is %n", sum);
%n
格式说明符用于存储到目前为止打印的字符总数,并需要一个 int *
参数。因为您传入的是 int
,所以会导致与之前相同的问题。
由于您可能想打印 sum
的值,因此您应该使用 %d
格式说明符:
printf("Total is %d", sum);
关于c - C 中的 NetBeans 退出错误代码值 -1.073.741.819,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49981302/