【发布时间】:2014-12-13 07:31:11
【问题描述】:
这个让我摸不着头脑。其中一个有效,另一个并不总是有效,我不知道为什么。到目前为止,第一批代码工作正常,但第二批代码偶尔会给出与第一批不同且不正确的结果。对于任何想知道的人,这是解决我想要制作的线性方程的更大程序的一部分。
我可以注意到两者之间的唯一区别是 firstEquation 数组大小不同,其中一个数组是全局声明的,而另一个是在主函数中声明的。我不明白为什么这很重要。
// First File (THIS ONE WORKS)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int co1 = 0;
int i = 0;
char firstEquation[50];
main ()
{
printf("Enter the first equation.. e.g '3x + 2' \n");
fscanf(stdin, " %99[^\n]", firstEquation);
printf("the equation you just entered is: %s \n", firstEquation);
for (i = 0; i < sizeof(firstEquation)/sizeof(firstEquation[0]); i++)
{
if (firstEquation[i] == 'x' || firstEquation[i] == ' '
|| firstEquation[i] == '+'|| firstEquation[i] == '-')
{
printf("%d \n", i);
co1 = i;
}
}
printf("the yintercept of your equation starts at the %d th element in the array", co1+1);
}
这是第二个。
// Second File (THIS ONE STUFFS UP SOMETIMES)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int co1 = 0;
int i = 0;
main ()
{
char firstEquation[100];
printf("Enter the first equation.. e.g '3x + 2' \n");
fscanf(stdin, " %99[^\n]", firstEquation);
printf("the equation you just entered is: %s \n", firstEquation);
for (i = 0; i < sizeof(firstEquation)/sizeof(firstEquation[0]); i++)
{
if (firstEquation[i] == 'x' || firstEquation[i] == ' '
|| firstEquation[i] == '+'|| firstEquation[i] == '-')
{
printf("%d \n", i);
co1 = i;
}
}
printf("the yintercept of your equation starts at the %d th element in the array", co1+1);
}
这是我在两个文件中输入的作为测试的方法:65x + 554
//OUTPUT OF FIRST BATCH OF CODE (GIVES CORRECT RESULT)
Enter the first equation.. e.g '3x + 2'
65x + 554
the equation you just entered is: 65x + 554
2
3
4
5
the yintercept of your equation starts at the 6 th element in the array
还有第二个。
//OUTPUT OF SECOND BATCH OF CODE (GIVES INCORRECT RESULT)
Enter the first equation.. e.g '3x + 2'
65x + 554
the equation you just entered is: 65x + 554
2
3
4
5
10
the yintercept of your equation starts at the 11 th element in the array
【问题讨论】:
-
你能在使用前memset你的内存吗...我的意思是“memset(firstEquation, 0x00, sizeof(firstEquation));”
-
fscanf()函数的这个参数:“%99[^\n]”在第一个程序中不正确,因为firstEquation只有50个字符长,不是99
-
fscanf() 不附加空字节,因此必须将输入缓冲区预初始化为所有 '\0' 或搜索 '\n' 并替换为 '\0 '
-
在字符数组上,此代码:sizeof(firstEquation[0] 将始终为 1。实际上,当遇到字符串终止符字节时,代码应该停止
-
非常感谢你们的回复,非常感谢。