pap*_*ton 1 c arrays for-loop scanf
我正在尝试创建一个能够计算拉格朗日多项式的程序,但我遇到了可能是一个微不足道的问题.我给出了一些x和y值,我应该使用这些值来近似某个其他x的函数.变量nodes指的是给出的x和y值对的数量.
我无法在x值的第一次迭代中读取,并且它直接跳过读取y值.即它只是打印x(0)然后y(0)而不让我输入x(0)的任何内容.对于第一个循环之后的任何循环,这不是问题.任何帮助,将不胜感激.
#include "stdio.h"
#include "math.h"
#define SIZE 40
int main(){
// Defining variables and arrays
int i, j, nodes;
float nodex[SIZE], nodey[SIZE], appx;
// Find how many nodes there are
printf("How many nodes are being referenced?\n");
scanf("%d", &nodes);
// Find what number we are approximating for x
printf("For what value of x are we approximating?\n");
scanf("%d", &appx);
for(i=0 ; i < nodes ; i++)
{
printf("\nEnter x(%d)", i);
scanf("%f", &nodex[i]);
printf("\nEnter y(%d)", i);
scanf("%f", &nodey[i]);
}
}
Run Code Online (Sandbox Code Playgroud)
如评论中所述:
您使用
%d与appx代替%f.在%d停止读取在小数点,而&nodex[0]输入继续在%d离开-在小数点.appx当然,价值也是垃圾.你应该测试返回值
scanf(); 你展示的每个电话都应该是1.您应该打印读取的值,这样您就知道读取的内容符合您的预期.
一些固定代码:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 40
static void err_exit(const char *msg)
{
fprintf(stderr, "%s\n", msg);
exit(EXIT_FAILURE);
}
int main(void)
{
// Defining variables and arrays
int nodes;
float nodex[SIZE], nodey[SIZE], appx;
// Find how many nodes there are
printf("How many nodes are being referenced?: ");
fflush(stdout);
if (scanf("%d", &nodes) != 1)
err_exit("failed to read number of nodes");
if (nodes < 3 || nodes > SIZE)
err_exit("number of nodes not in range 0..40");
// Find what number we are approximating for x
printf("For what value of x are we approximating?: ");
fflush(stdout);
if (scanf("%f", &appx) != 1)
err_exit("failed to read value");
for (int i = 0; i < nodes; i++)
{
printf("Enter x(%d): ", i);
fflush(stdout);
if (scanf("%f", &nodex[i]) != 1)
err_exit("failed to read x-value");
printf("Enter y(%d): ", i);
fflush(stdout);
if (scanf("%f", &nodey[i]) != 1)
err_exit("failed to read y-value");
}
printf("Approximating: %g\n", appx);
printf("%d nodes:\n", nodes);
for (int i = 0; i < nodes; i++)
printf("%2d (%g,%g)\n", i, nodex[i], nodey[i]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我假设你支持C99.如果没有,您需要int i;在循环外声明并for (i = 0; i < nodes; i++)用作循环.
汇编:
gcc -O3 -g -std=c11 -Wall -Wextra -Werror -Wmissing-prototypes -Wstrict-prototypes \
read-float-83.c -o read-float-83
Run Code Online (Sandbox Code Playgroud)
样品运行:
$ ./read-float-83
How many nodes are being referenced?: 5
For what value of x are we approximating?: 3.67
Enter x(0): 1.23
Enter y(0): 2.95
Enter x(1): 1.98
Enter y(1): 3.46
Enter x(2): 2.47
Enter y(2): 4.51
Enter x(3): 3.02
Enter y(3): 2.87
Enter x(4): 4.18
Enter y(4): -1.96
Approximating: 3.67
5 nodes:
0 (1.23,2.95)
1 (1.98,3.46)
2 (2.47,4.51)
3 (3.02,2.87)
4 (4.18,-1.96)
$
Run Code Online (Sandbox Code Playgroud)