none
C++转C#的一段代码 RRS feed

  • 问题

  • 有没有朋友可以帮助我把下面这段代码,改为C#的呢,谢谢了。

    #include "stdafx.h"
    #include<iostream>
    #include<iomanip>
    using namespace std;
    int totalWeight=0;
    const int  nMax=100;

    template<class Type> void Value(Type p[], Type w[], Type c,Type n,Type f[nMax][nMax])
    {
    for (int j = 0; j <= c; j++) 
    if(j>=w[0]) 
    f[0][j]=p[0];
    else 
    f[0][j]=0;
    // 
    for (int i =1; i<n; i++)

    for (int j = 0; j <= c;j++) 
    if(j>=w[i]&&f[i-1][j]<f[i-1][j-w[i]]+p[i])
    f[i][j]=f[i-1][j-w[i]]+p[i];
    else
    f[i][j]=f[i-1][j];

    }

    template<class Type> void compute(Type f[nMax][nMax], Type w[],Type p[], Type c, Type n, Type x[]) 
    {
     
    int c0=c, totalValue=0;
    for(int i=n-1;i>0;i--)
    if(f[i][c0]>f[i-1][c0]){
    x[i]=1;c0=c0-w[i];
    totalValue=totalValue+p[i];
    totalWeight=totalWeight+w[i];
    }
    else 
    x[i]=0;
    if(f[n-1][c]>totalValue){
    x[0]=1;
    totalWeight=totalWeight+w[0];
    }
    else
    x[0]=0;
    }

    int _tmain(int argc, _TCHAR* argv[]){
    int i, x[nMax],*weight,*price,volume,counts, value[nMax][nMax];
    char name[nMax][30]; 
    cout<<"请输入的容量"<<endl;
    cin>>volume; 
    cout<<"请输入物品的总个数"<<endl;
    cin>>counts; 
    weight=new int[counts]; 
    price=new int[counts]; 
    cout<<"请输入物品的名称:  重量:  价值:"<<endl;
    for(i=0;i<counts;i++)
    cin>>name[i]>>weight[i]>>price[i];
    //------------------------------------------------------======================
    Value(price, weight, volume, counts,value);
    compute(value, weight,price,volume,  counts, x);
    cout<<"装入的物品重量,价值,名字以表格的形式表示如下:)"<<endl;
    cout<<setw(10)<<"i"<<setw(12)<<"wieght[i]"<<setw(12)<<"price[i]"<<setw(12)<<"name[i]"<<endl;
    for(i=0;i<counts;i++){  
    if(x[i]==1)
    cout<<setw(10)<<i<<setw(10)<<weight[i]<<setw(10)<<price[i]<<setw(10)<<name[i]<<endl;
    }
    cout<<"装如的总重量:"<<totalWeight<<"总价值为:"<<value[counts-1][volume]<<endl;
    system("pause");
    delete []weight; 
    delete  []price;  
    return 0;


    2013年4月5日 12:04

答案