【发布时间】:2015-06-12 16:35:16
【问题描述】:
为了练习变量声明、占位符和 I/O 调用,我在正在学习的书中做了一个示例作业。但是,我一直遇到一个特殊的问题,即当我尝试声明多个字符变量用于输入时,即使编译器没有捕获任何语法错误,程序在执行时也只会返回一个字符变量.这是有问题的代码:
#include <stdio.h>
int main()
{
double penny=0.01;
double nickel=0.05;
double dime=0.1;
double quarter=0.25;
double value_of_pennies;
double value_of_nickels;
double value_of_dimes;
double value_of_quarters;
double TOTAL;
int P;
int N;
int D;
int Q;
char a,b;
//used "static char" instead of "char", as only using the "char" type caused a formatting error where only the latter character entered in its input would appear
printf("Please enter initials> \n");
printf("First initial> \n");
scanf("%s", &a);
printf("Second initial> \n");
scanf("%s", &b);
//"%s" was used as the input placeholder for type "char"
printf("%c.%c., please enter the quantities of each type of the following coins.\n", a, b);
printf("Number of quarters> \n");
scanf("%d", &Q);
printf("Number of dimes> \n");
scanf("%d", &D);
printf("Number of nickels> \n");
scanf("%d", &N);
printf("Number of pennies> \n");
scanf("%d", &P);
printf("Okay, so you have: %d quarters, %d dimes, %d nickels, and %d pennies.\n", Q, D, N, P);
value_of_pennies=penny*P;
value_of_nickels=nickel*N;
value_of_dimes=dime*D;
value_of_quarters=quarter*Q;
TOTAL=value_of_quarters+value_of_dimes+value_of_nickels+value_of_pennies;
printf("The total value of the inserted coins is $%.2lf. Thank you.\n", TOTAL);
//total field width omitted as to not print out any leading spaces
return(0);
}
这是转录的输出(“a”、“e”和四个“1”是样本任意输入值:
Please enter initials>
First initial>
a
Second initial>
e
.e., please enter the quantities of each type of the following coins.
Number of quarters>
1
Number of dimes>
1
Number of nickels>
1
Number of pennies>
1
Okay, so you have: 1 quarters, 1 dimes, 1 nickels, and 1 pennies.
The total value of the inserted coins is $0.41. Thank you.
我输入了字符“a”和“e”作为字符变量“a”和“b”的输入值,但只显示了“e”。另一方面,如果我在“char”变量声明中放置“静态”,则输入的char 值都将显示在相关的打印调用中。
为了将来参考,我想问一下为什么会发生这样的事情,以及声明中“静态”一词的价值。
(顺便说一句,我知道我可以简单地将“value_of_(在此处插入硬币)”变量作为常量宏。)
【问题讨论】:
-
我看不到您在代码中使用静态的位置。而且由于您只在 main 内部工作,静态不会有任何区别,除了使用
0初始化变量。也许您将static称为静态以外的东西。 -
整篇文章没有一个问号。
-
@bolov 等人:我没有声明我在此代码示例中放置了“静态”。我说,如果我插入了这个词,它就会按预期工作。我的问题是指我在此处发布的代码示例中的问题,特别是因为这对我来说是一个反复出现的问题。