【发布时间】:2014-02-27 21:18:32
【问题描述】:
我现在正在上编程课,并被要求创建一个程序来计算用户输入的多个数字的总和 - 然后计算总和的第 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;
}
【问题讨论】:
-
你试过在'if'语句上设置断点来看看'x'的值是多少?
-
要么像你一样将你的 x 定义为浮点数,并在 scanf 中使用“%f”,或者将其定义为双精度数,并使用“%lf”。现在你使用了错误的格式。
标签: c visual-studio while-loop