gpt4 book ai didi

C 程序崩溃... 'Read in and Output Various Data Types'

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

已更新

我在第 4 章问题 2 上遇到了一些麻烦,来自 Paul Kelly 的 “C 编程指南”

据我所知,我的语法是正确的,但是当程序到达第 36 行时,程序会自动填充 scanf(); 变量槽。

我似乎无法在任何地方找到解决这个问题的方法。

这是我的代码。我在第 36 行旁边放了一个标记


/* 
Program to demonstrate single scanf function
to read various data types and output results.

*/
#include <stdio.h>

main(){
int first;
int second, third, fourth;
float principle, rate, time;
char keyVal1, keyVal2;
char c;
int i;
float f;
double d;

printf("\nPlease Enter an Integer\n");
scanf("%d", &first);
printf("\nYou Entered %d\n", first);

printf("\nThank You, Please Enter 3 more integers\n");
scanf("%d %d %d", &second, &third, &fourth);
printf("\nYou Entered %d %d and %d\n", second, third, fourth);

printf("\nGreat,
now please enter decimal values for principle,
rate and time.\n");
scanf("%f %f %f", &principle, &rate, &time);
printf("\nYou Entered %.2f %.2f and %.2f\n", principle, rate, time);

printf("\nPlease Enter any 2 characters\n");
scanf(" %c %c", &keyVal1, &keyVal2);
printf("\nYou Entered %c and %c\n", keyVal1, keyVal2);

// ***36
printf("\nNow Enter any other character,
followed by an integer and 2 decimal numbers\n");***
scanf(" %c %d %f %lf ",&c, &i, &f, &d);
printf("\nYour character was %c.\nYour integer was %d\nYour
decimal numbers were %.2f and %.2lf\n", c, i, f, d);
}

最佳答案

scanf("%1s %1s", &keyVal1, &keyVal2);

使用 %c 说明符代替 %1s

scanf(" %c %c", &keyVal1, &keyVal2);

同样,

scanf("%c %d %f %lf ",&c, &i, &f, &d); 

%c前留一个空格-

scanf(" %c %d %f %lf ",&c, &i, &f, &d);

您需要留出空格,因为在 scanf 之后按下 ENTER '\n' 保留在 stdin .

关于C 程序崩溃... 'Read in and Output Various Data Types',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33057093/

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