我现在在编程类,并被要求创建一个程序,计算用户输入多个数字的总和 - 然后计算第n个总和的根源。如果他们输入的数字小于0,则循环应该丢弃小于0的数字,然后再次提问。我不能让这个(简单)循环正常工作
不幸的是,无论我输入什么数字 - 它显示“值需要大于零!”我试着在循环中放入一个fflush(stdin);
声明,但这似乎没有做任何事情。
这是我的代码。我非常感谢任何帮助。
#include "stdafx.h"
#include <stdio.h>
#include <math.h>
int main() {
int mTotalNums, mNth; //amount of numbers in set
float mProd = 1, x, mNroot;
printf("How many numbers are in the set?\n");
scanf("%i", &mTotalNums);
mNth = mTotalNums; //set the value of mTotalNums equal to mNth becuase we'll lose the original value of mTotalNums after the loop
while (mTotalNums > 0) {
printf("Input number: ");
scanf("%lf", &x);
if (x > 0) {
mProd *= x;
} else
printf("\nValue needs to be greater than zero!\n");
}
mNroot = pow(mProd, (1/mNth));
printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot);
return 0;
}
您是否尝试设置的“如果”语句中断点,看看有什么“x”的价值是什么? –
或者像你一样将x定义为float,并且在scanf中使用“%f”,或者将其定义为double,并使用“%lf”。现在你使用了错误的格式。 –