我想知道在StdMark> 50时如何使用字符串s1来打印成功。我需要在单向选择中这样做,换句话说,不使用else语句。
#include <iostream>
#include <string>
using namespace std;
int main()
{
int StdMark;
string s1;
s1="succuss";
cout <<"Enter The grade:"<<endl;
cin >>StdMark;
if(StdMark<50)
{
cout<<"fail";
}
return 0;
}
答案 0 :(得分:1)
我找到了问题的答案:
using System;
using System.Collections.ObjectModel;
using System.Windows;
namespace ListBoxUpdate
{
public partial class Window1 : Window
{
public ObservableCollection<StringWrapper> Strings { get; set; }
public class StringWrapper
{
public string Content { get; set; }
public StringWrapper(string content)
{
this.Content = content;
}
public static implicit operator StringWrapper(string content)
{
return new Window1.StringWrapper(content);
}
}
public Window1()
{
InitializeComponent();
this.Strings = new ObservableCollection<StringWrapper>(new StringWrapper[] { "one", "two", "three" });
this.DataContext = this;
}
void HandleButtonClick(object sender, RoutedEventArgs e)
{
string text = "";
for (int i = 0; i < Strings.Count; i++) {
text += Strings[i].Content + Environment.NewLine;
}
textBlock.Text = text;
}
}
}
答案 1 :(得分:1)
如果您不想使用if
/ else
,则有以下几种选择:
使用?:
三元运算符:
#include <iostream>
#include <string>
using namespace std;
int main()
{
int StdMark;
cout << "Enter The grade:" << endl;
cin >> StdMark;
cout << (StdMark < 50) ? "fail" : "success";
return 0;
}
声明包含"success"
和"fail"
的2元素字符串数组,然后使用<
运算符的输出作为该数组的索引:< / p>
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char* str[2] = {"success", "fail"};
int StdMark;
cout << "Enter The grade:" << endl;
cin >> StdMark;
cout << str[StdMark < 50];
return 0;
}