2014-02-27 71 views
2

我现在在编程类,并被要求创建一个程序,计算用户输入多个数字的总和 - 然后计算第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; 
} 
+0

您是否尝试设置的“如果”语句中断点,看看有什么“x”的价值是什么? –

+0

或者像你一样将x定义为float,并且在scanf中使用“%f”,或者将其定义为double,并使用“%lf”。现在你使用了错误的格式。 –

回答

1

尝试这些修改程序(添加的注释与所做的更改)

#include "stdafx.h" 
#include <stdio.h> 
#include <math.h> 

int main() { 

    //amount of numbers in set 
    int mTotalNums, mNth; 
    // Change to double for added precision 
    double mProd = 1.0, x, mNroot; 

    printf("How many numbers are in the set?\n"); 
    scanf("%i", &mTotalNums); 

    // Set the value of mTotalNums equal to mNth becuase 
    // we'll lose the original value of mTotalNums after the loop 
    mNth = mTotalNums; 

    // Don't forget to decrement the loop counter 
    while (mTotalNums-- > 0) { 
     printf("Input number: "); 
     scanf("%lf", &x); 
     if (x > 0) { 
      mProd *= x; 
     } else { 
      printf("\nValue needs to be greater than zero!\n"); 
     } 

    } 

    // Change to 1.0 to force compiler to treat as a double 
    mNroot = pow(mProd, (1.0/mNth)); 

    printf("\nThe nth root of the product of %i terms is: %.2f\n", mNth, mNroot); 

    return 0; 
} 

你提到“计算总和的n次方根”,但你的循环显然清点的累积产。要改变它来计算总和,请尝试以下补充:

// Declare a sum variable 
double sum = 0; 
// Sum inside your while loop 
sum += x; 
// Calculate the nth root of the sum instead 
mNroot = pow(sum, (1.0/mNth)); 
+0

我不是故意说“总和的第n根”,我的意思是“产品的第n根”。这是我的不好。不过,我很感激你要重写我的程序。这非常有帮助! – Nxt3

2

"%lf"是一个double scanf函数的格式,但x被声明为float。 要扫描浮点数,必须使用%f格式。

还要注意,mTotalNums在循环中不递减,因此它永远不会从 终止。

2

阅读文档scanf(3)。由于x被声明为float,因此使用%f作为scanf格式控制字符串。此外,请考虑scanf的结果(如果成功读取一个项目,则结果为1)。

您应该在编译器中启用所有警告和调试信息,然后学习如何使用调试器(特别是逐步运行程序,显示局部变量等)。

(在Linux上,如果与gcc -Wall -g编译,你会得到一个有用的警告,gdb调试器将是有益的...)

1

添加的printf命令来查看您的变量包含你在检查之前你的逻辑陈述。

你还需要做一些事情来为你的while循环增加/减少你的变量......目前没有什么改变mTotalNums,所以它将是一个无限循环。

while (mTotalNums > 0) { 
     printf("Input number: "); 
     scanf("%lf", &x); 
     printf("x=%d", x); 
     if (x > 0) { 
      mProd *= x; 
     } else 
      printf("\nValue needs to be greater than zero!\n"); 
     mTotalNums--; 
    }