幫我用C編個用FOR語句的求和程序
給,已經編譯運行確認:
#include<conio.h>
#include<stdio.h>
int main()
{
int i,j=1,n;
float sum=0;
printf("please input n: \n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
sum+=1.0/j;
j+=2;
}
printf("result: %f",sum);
getch();
return 1;
}
用for循環求和
如果還是用MyInput的話,要加一個類;sum定義的地方錯了;data沒有初始化;沒有import 。
import *.*;
public class For求和1
{
public static void main(String[] args)
{
int data=-1;
int sum=0;
for (;data!=0;sum=sum+data)
{
*n("輸入一個整數 輸入0則結束");
data=*t();
}
*n("這個和是:"+ sum);
}
}
class MyInput
{
public static String readString()
{
BufferedReader br
=new BufferedReader(new InputStreamReader(*),1);
String string=" ";
try
{
string=*ne();
}
catch (IOException ex)
{
*n(ex);
}
return string;
}
public static int readInt()
{
return *nt(readString());
}
public static double readDouble()
{
return *ouble(readString());
}
}
應用 for 循環語句求和 4*(1-1/3+1/5-1/7+1/9+……+1/10000001)
public static void main(String[] args) {
// TODO Auto-generated method stub
double s = 0;
boolean type = true;
for(double i =1;i<=10000001;i=i+2){
if(type){
s = s + 1/i;
type = false;
}else {
s = s - 1/i;
type = true;
}
}
s = s * 4;
*n(s);
}
double s = 0; //用于存放總和boolean type = true; //用于區分是加還是減,當為true是為加,false為減
//循環,每次i加2for(double i =1;i<=10000001;i=i+2){if(type){//開始type=true;所以加s = s + 1/i; //累計和type = false; //加后要減,所以改為false}else {//減的情況s = s - 1/i;type = true;//減后改變為true;進行下次加}}s = s * 4; //最后結果出乘以4得到最后結果;*n(s);//輸出}
看的懂嗎??
我覺得這應該是一道算法題,不是用循環寫的,因為運算量很大,循環效率低。..這道題是需要找規律的
有規律才能用循環,失去了規律想用循環都不能了