
using System.Collections.Generic;
using System.Text;
//针对字符串s="0123456789";求取偶数位数之和,奇数位之差
namespace 练习2
{
class Calculate {
public int even(string s) { //偶数之和
int i = 0,b=0; //既然foreach循环内不允许访问下标就设一个计数器i,用它来判断是否跌倒到偶数位了;既然foreach内不让给char x变量++那就声明一个变量b每次都赋值给b
foreach (char x in s)
{
// b = Convert.ToInt32(x);
Console.WriteLine(b);
if (i % 2 == 0) //如果迭代到了偶数位,就让当前的x加到B里面
b+=x;
i++; //每次迭代都要++
} return b;
}
//public int odd(string s) { //奇数之和
//}
}
class Test
{
static void Main(string[] args)
{
string s = "0123456789";//已知条件
Calculate cal = new Calculate();
Console.WriteLine(cal.even(s));
}
}
}
我就烦foreach这个东西 如果可以把s转成int型数组就好了 烦死了!!
1楼的 我真看不明白。。 i+=2 这个意思是什么?
随便改了下 能运行了
不明白你的誉毁盯意思
using System;
using System.Collections.Generic;
using System.Text;
//针对字符串s="0123456789";求取偶数位数之和,奇数位之差
namespace 练习2
{
class Calculate
{
public int even(string s)
{ //偶数之和
char[] tt=s.ToCharArray ();
int sum=0; //用来合计
//int i = 0, b = 0; //既然foreach循环内不允许访问下标就设一个计数器i,用它来判断是否跌倒到偶数位了;既然foreach内不让给char x变量++那就声明一个变余穗量b每次都赋值给b
foreach (char x in tt)
{
if ((Convert.ToInt32(x-48)) % 2 == 0) //如果迭代到了偶数位,就让当前的x加到B里面
{
sum += (x-48);
Console.WriteLine(x - 48);
}
// i++; //每次迭代都要++
//Console.WriteLine(x-48);
} return sum;
}
//public int odd(string s) { /庆和/奇数之和
//}
}
class Test
{
static void Main(string[] args)
{
string s = "0123456789";//已知条件
Calculate cal = new Calculate();
Console.WriteLine(cal.even(s));
Console.ReadKey();
}
}
}
string s = "0123456789"早型;
int a = 0;//乘积
for (int i = 1; i <陆键猜亮判 s.Length; i+=2 )
{
if (i > s.Length) return;
//算出偶乘积
a+= Convert.ToInt32(s.Substring(i, 1)) * Convert.ToInt32(s.Substring(i - 2, 1));
}
类型转换。。
int[] array =new int[10];
int i =0;
foreach(string str in s)
{
array[i]=Convert.ToInt32(str)
i++;
}
就可以把字符串用int型丢到袜清数茄好首组里
i+=2是i=i+2 的意思。。颤数基本上。。
string s="123456";
char[] arr=s.tochararray();
.................