A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 李龙祺 中级黑马   /  2012-12-7 17:34  /  1672 人查看  /  6 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

我是初学者刚学习了算术运算,结合前面学的用户输入写了一段代码。
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace _06算术运算
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             Console.WriteLine("输入你的成绩语文是");
  12.             string chinese = Console.ReadLine();
  13.             Console.WriteLine("数学");
  14.             string math = Console.ReadLine();
  15.             Console.WriteLine("英语");
  16.             string english = Console.ReadLine();

  17.             //int chinese = 90;
  18.             //int math = 80;
  19.             //int english = 85;
  20.             int sum = chinese + math + english;
  21.             int  pj = sum/3;
  22.             Console.WriteLine("你的总成绩是{0},平均分是{1}",sum,pj);
  23.             
  24.             Console.ReadKey();
  25.         }
  26.     }
  27. }
复制代码
报错   怎么解决

QQ截圖20121207173357.png (5.3 KB, 下载次数: 31)

QQ截圖20121207173357.png

评分

参与人数 1技术分 +1 收起 理由
郑文 + 1

查看全部评分

6 个回复

倒序浏览
这个错误提示出现在22行,sum为int类型,而chinese,math,english为string类型。
你可以这样修改
int sum=convert.Toint32(chinese)+convert.Toint32(math)+convert.Toint32(english);

评分

参与人数 1技术分 +1 收起 理由
郑文 + 1

查看全部评分

回复 使用道具 举报
chinese,math,english声明的时候是string字符串类型,而在计算int sum = chinese + math + english;需要把这三个变量转为int类型,这个可以这么理解:int数字加数字才等于数字嘛
怎么转呢?用int.parse()就可以了。()内必须是string类型,而且必须是可以转为数字的string,比如aa就不能变为数字,会报错。
  1. int sum = int.Parse(chinese) +int.Parse( math) + int.Parse(english);
复制代码

评分

参与人数 1技术分 +1 收起 理由
郑文 + 1

查看全部评分

回复 使用道具 举报
顶~~~~~~顶
回复 使用道具 举报
多谢了
回复 使用道具 举报
变量的 类型不统一 啊,除了上面的改法外也可以这样改  :第13行 int chinese=Convert.ToInt32(Cnsole.WiteLine()) ;
                                                                                      第15行 int math=Convert.ToInt32(Cnsole.WiteLine()) ;
                                                                                      第17行 int engilsh=Convert.ToInt32(Cnsole.WiteLine()) ;

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
汪磊 中级黑马 2012-12-9 22:09:04
7#
字符串类型相加得到的是字符串拼接而不是数学意义上的算数加法, 用Convert.Toint32(str);转换一下数据类型,  建议去复习一下数据类型和运算符!

评分

参与人数 1技术分 +1 收起 理由
宋天琪 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马