【发布时间】:2018-03-03 21:01:27
【问题描述】:
我正在尝试创建一个能够计算拉格朗日多项式的程序,但我遇到了可能是一个微不足道的问题。我得到了一些 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]);
}
}
【问题讨论】:
-
运行此代码时
nodes分配了什么值? -
您正在使用
%d和appx,而不是%f。%d停止在小数点处,&nodex[0]在%d停止的地方恢复 - 在小数点处。当然,appx中的值也是垃圾。您应该测试来自scanf()的返回值;对于您显示的每个呼叫,它应该是1。您应该打印读取的值,以便您知道读取的内容与您的预期相符。 -
谢谢@JonathanLeffler。这清除了它。